我是ractive.js的新手,想要将它与backbone.js集成。我找到了一个ractive的主干适配器,但是没有找到一个可以有效使用它的样本。 需要一个示例来解释如何将ractive.js用作backbone.js中的视图组件
答案 0 :(得分:3)
由于官方演示似乎失败,我能够根据其余文档整理一个简单的演示。
基本上包括ractive和ractive adapter for backbone之后的主干和依赖关系,然后在你的视图中,render方法初始化一个新的ractive视图,将主干视图的元素,模板和模型数据传递给{{分别为1}},el
和template
,如下例所示。
对于单向绑定,请使用模型getter方法,如data
对于双向绑定,请直接引用{{{{model.get('prop')}}
}}
另外,为了避免内存泄漏的可能性,请覆盖骨干网视图的model.attributes.name
方法,并在删除之前将其销毁。
希望评论解释这个过程:
remove

// Nothing special, create a model instance with data
var model = new Backbone.Model({
name: "John"
});
// Backbone view constructor
var View = Backbone.View.extend({
template: $('#ractiveTest').html(),
initialize: function() {
this.render();
},
events: {
'click button': 'remove'
},
render: function() {
//initialize ractive view as part of rendering
this.ractive = new Ractive({
el: this.el, // pass the view's element to ractive
template: this.template, // pass the view's template to ractive
data: {
user: this.model // pass view's model data to ractive
}
});
},
//override view's remove method to destroy ractive instance as well
remove: function() {
// Just for added safety
this.ractive.teardown();
Backbone.View.prototype.remove.call(this);
}
});
// initialize the view and pass in the model.
var view = new View({
model: model
});
// append the view to DOM
view.$el.appendTo(document.body);

我觉得有点奇怪,我们必须在模板中为<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.1/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/0.7.3/ractive.js"></script>
<script src="//cdn.jsdelivr.net/ractive.adaptors-backbone/latest/ractive-adaptors-backbone.min.js"></script>
<script type="text/template" id="ractiveTest">
<label>
Enter your name:
<input value="{{user.attributes.name}}">
</label>
<p>Hello, {{user.get('name')}}!</p>
<button>remove</button>
</script>
进行单向绑定,并user.get('name')
用于双向绑定。
它可能已在Backbone适配器中被抽象出来,例如像user.attributes.name
那样rivets。