Reputation: 1670
I am new to Backbone, and I'm trying to get a form to submit from a tutorial.
I keep getting the following error:
Uncaught TypeError: Cannot call method 'add' of undefined
for the the line this.collection.add( book );
What do I need to correct?
App.Views.AddBook = Backbone.View.extend({
events: {
'click #add': 'submit'
},
submit: function(e) {
e.preventDefault();
var formData = {};
$('#addBook div').children('input').each(function(i, el) {
if($(el).val() !== '') {
formData[ el.id ] = $(el).val();
}
});
var book = new App.Models.Book( formData );
this.collection.add(book);
}
});
var booksCollection = new App.Collections.Books([
{
title: 'JS: The Good Parts',
author: 'Douglas Crockford',
releaseDate: '2008'
},
{
title: 'The Little Book on CoffeeScript',
author: 'Alex MacCaw',
releaseDate: '2012'
}
]);
var addBook = new App.Views.AddBook({ el: $('#addBook') });
<form id="addBook" action="#">
<div>
<label for="title">Title: </label><input id="title" type="text" />
<label for="author">Author: </label><input id="author" type="text" />
<label for="releaseDate">Release date: </label><input id="releaseDate" type="text" />
<br>
<button class="btn" id="add">Add</button>
</div>
</form>
Upvotes: 0
Views: 82
Reputation: 101513
You need to pass in your booksCollection
to your view, like this:
var addBook = new App.Views.AddBook({
collection: booksCollection,
el: $('#addBook')
});
If you don't, this.collection
in the view context won't be defined which is why you're getting that error. The collection
parameter in the view's initialisation is special in that Backbone will assign it to this.collection
inside the view.
Upvotes: 3