Reputation: 1821
I am writing a slightly modified version of the Backbone Todos app commonly found online, using books instead. My Backbone version is 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. My understanding (reading this - http://backbonejs.org/#Collection-create), is that creating a model will trigger an add
event on the collection. I tried using bind
instead of on
, but that didn't work. I also tried this.listenTo
in place of on
, but that threw an error, saying, this.listenTo
is not defined. Please help. Thanks!
Upvotes: 0
Views: 213
Reputation: 3819
I've never made extensive use of ES6 arrow functions, but I think they may be causing you problems here. As I understand it, arrow functions do not bind the this
object. 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.
Try replacing:
initialize: () => {
// ...
},
with:
initialize: function() {
// ...
},
and similar for your other methods. I think that will clear up a lot of problems.
Upvotes: 2