Rivets.js - 数据绑定和模板系统使用详解3(组件封装、默认配置的修改)
相关文章系列:
Rivets.js - 数据绑定和模板系统使用详解1(基本介绍、绑定器的使用)
Rivets.js - 数据绑定和模板系统使用详解2(格式化器的使用、函数调用)
[当前文章] Rivets.js - 数据绑定和模板系统使用详解3(组件封装、默认配置的修改)
Rivets.js - 数据绑定和模板系统使用详解1(基本介绍、绑定器的使用)
Rivets.js - 数据绑定和模板系统使用详解2(格式化器的使用、函数调用)
[当前文章] Rivets.js - 数据绑定和模板系统使用详解3(组件封装、默认配置的修改)
七、组件封装
Rivets.js 允许我们可以自定义一些组件,从而实现视图的复用。
1,封装一个计数器组件
组件内有加减两个按钮,点击后会对绑定的数据进行 +1 或 -1。
按钮旁还有个文本标签,显示当前的数值。
//组件
rivets.components['counter'] = {
//返回组件使用的模板
template: function() {
return '<button rv-on-click="increment">+</button>' +
'<button rv-on-click="decrement">-</button>' +
'<span> {data.nameAttr}:{data.countAttr}</span>';
},
//返回组件对应的视图模型
initialize: function(el, attributes) {
return new counterViewModel(attributes);
}
};
//定义组件对应的视图模型
function counterViewModel(attributes) {
//组件数据
this.data = attributes;
//加按钮调用的方法
this.increment = function (context, ev) {
// Rivets 会将 count-attr 重命名为 countAttr
ev.data.countAttr++;
};
//减按钮调用的方法
this.decrement = function (context, ev) {
ev.data.countAttr--;
};
}
2,计数器组件使用样例
(1)下面是样例代码
/********* 下面是js代码 ********/
//数据模型
var data = {
name: "商品库存",
value: 10
}
//绑定并显示模型
rivets.bind($("#detail"), {
data: data
});
/********* 下面是html代码 ********/
<section id="detail">
<counter count-attr="data.value" name-attr="data.name"/>
</section>
(2)运行效果图

八、修改默认配置
通过 rivets.configure,我们可以修改 Rivets 的相关配置,具体有如下配置项:rivets.configure({
// 模板中的属性前缀
prefix: 'rv',
// 预加载模板实现初始数据绑定
preloadData: true,
// sightglass根路径
rootInterface: '.',
// 用于文本绑定的模板分隔符
templateDelimiters: ['{', '}'],
// rv-each绑定的index索引
iterationAlias : function(modelName) {
return '%' + modelName + '%';
},
// on-*事件绑定响应函数的参数
handler: function(target, event, binding) {
this.call(target, event, binding.view.models)
},
// rivets自0.9起, 函数不会在表达式中自动执行。如果需要向后兼容,则将此参数设置为true
executeFunctions: false
})
