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>
The running effect is as follows:
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" });
Use in custom tags:
[code]this.mixin("defaultData"); // 现在this拥有了author和email属性了
Small pitfalls encountered
Pay attention to the number sequence of mixin. The following attributes will overwrite the previous attributes.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 (m.sbmmt.com)!