在触发事件之前处理 Backbone 集合获取的数据
Process Backbone collection fetched data before firing event
我有 Backbone 集合和集合视图与监听器:
this.listenTo(this.collection, 'reset', this.render);
然后在某个时候我会这样做:
myCollection.fetch({
reset: true,
success: myCallback
})
我想要的是根据页面上发生的情况对模型进行一些更改(甚至可能删除或替换其中的一些模型)。我想在 之前 渲染视图。目前我正尝试在 myCallback
中执行此操作,但看到它在渲染后调用。
如何在任何事件发生之前处理获取的数据?
您可以使用 parse
收集方法在事件触发之前修改获取的响应,例如:
Backbone.Collection.extend({
parse: function(response){
// modify response here
return response;
}
});
或者出于某种原因,如果您想 运行 在创建模型后在实际模态实例上使用您的代码,那么您可以手动调用渲染而不是像这样的事件侦听器:
myCollection.fetch({
reset: true,
success: function(collection, response){
// modify response here
view.render();
}
})
或者有一个不同的回调来操纵模态,然后像这样调用渲染:
Backbone.View.extend({
initialize: function(){
this.listenTo(this.collection, 'reset', this.preRender);
},
preRender: function(){
// manipulate models here
this.render();
},
render: function(){
// Actual rendering here
}
});
我有 Backbone 集合和集合视图与监听器:
this.listenTo(this.collection, 'reset', this.render);
然后在某个时候我会这样做:
myCollection.fetch({
reset: true,
success: myCallback
})
我想要的是根据页面上发生的情况对模型进行一些更改(甚至可能删除或替换其中的一些模型)。我想在 之前 渲染视图。目前我正尝试在 myCallback
中执行此操作,但看到它在渲染后调用。
如何在任何事件发生之前处理获取的数据?
您可以使用 parse
收集方法在事件触发之前修改获取的响应,例如:
Backbone.Collection.extend({
parse: function(response){
// modify response here
return response;
}
});
或者出于某种原因,如果您想 运行 在创建模型后在实际模态实例上使用您的代码,那么您可以手动调用渲染而不是像这样的事件侦听器:
myCollection.fetch({
reset: true,
success: function(collection, response){
// modify response here
view.render();
}
})
或者有一个不同的回调来操纵模态,然后像这样调用渲染:
Backbone.View.extend({
initialize: function(){
this.listenTo(this.collection, 'reset', this.preRender);
},
preRender: function(){
// manipulate models here
this.render();
},
render: function(){
// Actual rendering here
}
});