Jai*_*era 5 backbone.js marionette
我有一个带有搜索面板和结果数据集合的Marionette CompositeView.
我想在以下情况下调用函数:
我是这样做的:(但"afterRender"函数被调用两次)
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
// TEMPLATE
template: Handlebars.compile(templates.find('#composite-template').html()),
// ITEM VIEW
itemView: App.Item.View,
// ITEM VIEW CONTAINER
itemViewContainer: '#collection-block',
//INITIALIZE
initialize: function() {
this.bindTo(this,'render',this.afterRender);
},
afterRender: function () {
//THIS IS EXECUTED TWICE...
}
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
==========================编辑======================= ===========
我这样解决了,如果你有观察请告诉我.
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
//INITIALIZE
initialize: function() {
//this.bindTo(this,'render',this.afterRender);
this.firstRender = true;
},
onRender: function () {
if (firstRender) {
//DO STUFF HERE..............
this.firstRender = false;
}
}
});
Run Code Online (Sandbox Code Playgroud)
Der*_*ley 11
Marionette提供了一个onRender内置于其所有视图的方法,因此您可以摆脱this.bindTo(this, 'render', this.afterRender)调用:
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
// TEMPLATE
template: Handlebars.compile(templates.find('#composite-template').html()),
// ITEM VIEW
itemView: App.Item.View,
// ITEM VIEW CONTAINER
itemViewContainer: '#collection-block',
//INITIALIZE
initialize: function() {
// this.bindTo(this,'render',this.afterRender); // <-- not needed
},
onRender: function () {
// do stuff after it renders, here
}
});
Run Code Online (Sandbox Code Playgroud)
但是为了在不渲染集合时不让它工作,你必须向onRender方法添加逻辑,以检查集合是否被渲染.
这在很大程度上取决于当没有从集合中呈现项目时,您尝试对渲染做什么.
例如......如果要呈现"找不到项目"消息,可以使用内置emptyView配置作为合成视图.
NoItemsFoundView = ItemView.extend({
// ...
});
CompositeView.extend({
emptyView: NoItemsFoundView
});
Run Code Online (Sandbox Code Playgroud)
但是如果你有一些特殊的代码需要运行并执行这个选项未涵盖的某些事情,那么你将不得不放入一些你自己的逻辑.
CompositeView.extend({
onRender: function(){
if (this.collection && this.collection.length === 0) {
// do stuff here because the collection was not rendered
}
}
});
Run Code Online (Sandbox Code Playgroud)
只需使用onShow功能
Backbone.Marionette.ItemView.extend({
onShow: function(){
// react to when a view has been shown
}
});
Run Code Online (Sandbox Code Playgroud)
http://marionettejs.com/docs/marionette.view.html#view-onshow