我在重新设计应用程序的主要功能时第一次使用主干。目标是使用相同的主干集合/视图代码来管理同一页面上的多个不同列表 - 功能都相同,只是数据发生了变化。
到目前为止,我已经取得了成功,但发现了一个我无法弄清楚的问题。当您从表单输入添加新项目时,视图会处理它并调用集合的 add 函数,该函数使用 ajax 保存它。完成后,集合调用一个“additem”事件,该事件应该触发视图重新呈现。
但是,发生的情况是仅调用最近加载的视图中的事件。即使我完全更改了事件名称,所以它们是前缀并且对于每个视图必须是唯一的 - 这让我感到困惑。
删除了很多代码,但有问题的部分如下。在这个代码示例中,我试图为我们需要的每种列表类型添加事件的前缀,但不管它在错误的视图上调用事件是什么。
// A collection is made to manage the data - saves to the server, loads, updates, etc
var ListItems = Backbone.Collection.extend({
initialize: function(models, options) {
this.url = options.url;
this.options = options;
},
/**
* We'll use a custom addItem handler so that we're not triggering
* events or ajax requests on .add(), since .fetch() uses it
*/
addItem: function(obj,ajax_elem){
self_col = this;
$.ajax({
type: 'POST',
url: this.options.add_url,
data: obj,
success: function(resp){
if(resp.success === true){
console.log('collection calls ep ' + self_col.options.ep+':addItem');
Backbone.Collection.prototype.add.call(self_col, {text:obj.text,id:resp.id} );
self_col.trigger(self_col.options.ep+':addItem');
} else {
self_col.trigger(self_col.options.ep+':error', resp.errors);
}
// ... rest of stuff
// View manages rendering the items to the page, etc
ListView = Backbone.View.extend({
initialize: function(){
self = this;
this.ep = self.$el.attr('id');
this.collection.bind(this.ep+":addItem",function(){
console.log('view thinks ep is: ' + self.ep+":addItem");
console.log(self.$el);
self.render();
$(window).trigger('Snowy:ajax:stop', self.$el.find(':submit'));
});
// Load the category list
categoryList = new ListView({
collection: new ListItems( INIT_CATEGORIES, {
ep: 'categories',
// other opts
}),
el: $("#categories")
});