listento
僅觸發全局集合,而不是我在創建時傳遞給視圖的集合。Backbone.js`listento`未針對已過濾的集合進行觸發
例如:
var MyView = Backbone.View.extend({
initialize: function() {
this.listenTo(notes, "add", this.test); // <--- THIS FIRES
this.listenTo(this.collection, "add", this.test); // <-- THIS DOES NOT FIRE
},
test: function() {
console.log('model added to collection')
}
});
我過濾的集合中通過像這樣在創建視圖時:
var notesFilteredByGroup = notes.filter_group(123);
var myView = new MyView({
collection: notesFilteredByGroup
});
這裏是Notes
集合:
Notes = Backbone.Collection.extend({
url: '/notes',
model: Note,
filter_group: function(groupNum) {
filtered = this.filter(function(note) {
return note.get('groupNum') === groupNum;
});
return new Notes(filtered);
}
});
當我提交了一個新的筆記,它更新了全球收藏就好了。我如何告訴notesFilteredById
或this.collection
收聽增加的模型?
編輯:
添加請求的代碼,改變了一些變量名,使問題更加清晰
注提交代碼:
var AddNoteView = Backbone.View.extend({
tagName: 'div',
template: _.template(AddNoteTemplate),
events: {
'click #noteSubmitButton': 'submit'
},
initialize: function() {
this.render();
},
render: function() {
var template = this.template(this.model.toJSON());
this.$el.html(template);
return this;
},
submit: function(event) {
event.preventDefault();
var newNote = {
text: $('#text').val(),
groupNum: $('#groupNum').val(),
};
this.collection.create(newNote, {wait: true});
}
});
實例化AddNoteView:
var notes = new Notes;
notes.fetch();
var addNoteView = new AddNoteView({
collection: notes
});
你能告訴,你添加到集合 –
什麼'這個代碼。 collection'對應於'AddNoteView' –