Home > Web Front-end > JS Tutorial > body text

riot.js learning [2] mixin

黄舟
Release: 2017-01-16 16:01:51
Original
1521 people have browsed it

Mixin Introduction

In riot.js, there is a very important concept, which is mixin. As the name suggests, its approximate function is "mixing".

Mix the properties and methods of the object into the current context. The common understanding is that it is the this object.

Look at a "chestnut":

[code]<!Doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Riot.js测试02, Mixin</title>
    <script type="text/javascript" src="riot.js"></script>
    <script type="text/javascript" src="compiler.js"></script>
</head>
<body>
    <todo title="da宗熊"></todo>
</body>
<script type="riot/tag">
    <todo>
        <h1>{ title || "" }</h1>
        <p>年龄: { this.getAge() } </p>
        <p>身高:{ height }cm</p>

        // 这里可以省略script标签
        this.title = opts.title || "";
        // 调用mixin,mixin拿到的,是window.mixinObj
        // 也可以混合多个 this.mixin(a, b...);
        this.mixin(mixinObj);
    </todo>
</script>
<script type="text/javascript">
    var mixinObj = {
        age: 10,
        height: 180,
        getAge: function(){
            return this.age;
        }
    };
    riot.mount("todo");
</script>
</html>
Copy after login

The running effect is as follows:

riot.js learning [2] mixin

You see, through this.mixin(mixinObj); window The properties and methods of .mixinObj are all reflected in this.

Note: mixin only shallowly copies the object, so when multiple custom tags share the mixin object, be careful of mutual influence

Declarative mixin

Parameters of mixin, Not just objects, but also strings. But when using strings, you must register a mixin in riot in advance.

Registration method:

[code]// 如果要跨项目共享 mixin,可以考虑在riot里注册一个,而不是使用window级对象
riot.mixin("defaultData", {
    author: "da宗熊",
    email: "1071093121@qq.com"
});
Copy after login

Use in custom tags:

[code]this.mixin("defaultData"); // 现在this拥有了author和email属性了
Copy after login


Small pitfalls encountered

Pay attention to the number sequence of mixin. The following attributes will overwrite the previous attributes.

The attributes of mixin will even overwrite the attributes of this.

Do not overwrite them. The properties and methods that come with riot.js, such as: opts, update, on, off, trigger, etc.

The above is the content of riot.js learning [2] mixin, please pay attention to more related content PHP Chinese website (www.php.cn)!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template