[英]Backbone collection add event not firing
I am writing a slightly modified version of the Backbone Todos app commonly found online, using books instead. 我正在编写通常在网上找到的Backbone Todos应用程序的稍作修改的版本,而是使用书籍。 My Backbone version is 1.3.3.
我的骨干网版本是1.3.3。 Like the example, for now I am just trying to display a book title added by the user in an input list.
像示例一样,现在我只是试图显示用户在输入列表中添加的书名。 My code (partial) is given below:
我的代码(部分)如下:
app.BookList = Backbone.Collection.extend({
model: app.Book,
// For temp use, to be replaced with URL
localStorage: new Backbone.LocalStorage('BookList')
});
app.bookList = new app.BookList();
app.AppView = Backbone.View.extend({
el: '#app',
initialize: () => {
this.input = this.$('#book-name');
app.bookList.on('change', this.addOneBook, this);
app.bookList.fetch();
},
events: {
'keypress #book-name': 'createNewBookModel'
},
addOneBook: (book) => {
console.log('BOOK: ', book);
const b = new app.BookView({ model: book });
this.$('#bookList').append(b.render().el());
},
createNewBookModel: (e) => {
if (e.which === 13) {
e.preventDefault();
app.bookList.create({ title: this.input.val().trim() });
this.input.val('');
}
}
});
app.appView = new app.AppView();
My problem is the addOneBook
event is not firing, after the createNewBookModel
event has fired and completed. 我的问题是,在
createNewBookModel
事件已触发并完成后, addOneBook
事件未触发。 My understanding (reading this - http://backbonejs.org/#Collection-create ), is that creating a model will trigger an add
event on the collection. 我的理解(阅读本文-http://backbonejs.org/#Collection-create )是,创建模型将触发集合上的
add
事件。 I tried using bind
instead of on
, but that didn't work. 我尝试使用
bind
而不是on
,但这没有用。 I also tried this.listenTo
in place of on
, but that threw an error, saying, this.listenTo
is not defined. 我也尝试使用
this.listenTo
代替on
,但这引发了错误,说this.listenTo
未定义。 Please help. 请帮忙。 Thanks!
谢谢!
I've never made extensive use of ES6 arrow functions , but I think they may be causing you problems here. 我从未广泛使用过ES6 箭头功能 ,但我认为它们可能在这里给您带来麻烦。 As I understand it, arrow functions do not bind the
this
object. 据我了解,箭头函数不会绑定
this
对象。 While your functions are executing, your this
will evaluate to undefined or maybe even the window
parent object, but I think you want it to evaluate to the backbone object. 在执行函数时,
this
函数的值将评估为undefined,甚至可能是window
父对象,但我认为您希望其对主干对象进行评估。
Try replacing: 尝试更换:
initialize: () => {
// ...
},
with: 与:
initialize: function() {
// ...
},
and similar for your other methods. 和其他方法类似。 I think that will clear up a lot of problems.
我认为这将解决许多问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.