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
orthis.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
});