Reputation: 7835
This is from my Backbone View. But I keep getting the following error:
Uncaught TypeError: Cannot call method 'add' of undefined
.
How can I keep this so that I can add a new model to my collection?
addGroupModal: function() {
$('#add-group-modal').modal('show');
// Manual Event Listener for Submit Button
$("#add-group-submit-button").click(function(){
var newGroup = new KAC.Models.KeepAContactGroup({ name: '123', list_order: '2' });
console.log(newGroup)
newGroup.save();
this.collection.add(newGroup)
});
},
Upvotes: 1
Views: 75
Reputation: 7295
In scope of your anonymous function (callback) this
represents not your view but the prototype (class) created by that function.
So that you should force that function to use particular this
context.
You can use either Underscore/LoDash _.bind()
method
or native Function.prototype.bind() (for all major browsers and IE > 8).
addGroupModal: function() {
$('#add-group-modal').modal('show');
// Manual Event Listener for Submit Button
$("#add-group-submit-button").click(_.bind(function() {
var newGroup = new KAC.Models.KeepAContactGroup({
name: '123',
list_order: '2'
});
console.log(newGroup);
newGroup.save();
this.collection.add(newGroup);
}, this));
}
Native bind:
$("#add-group-submit-button").click(function() {
// ...
}.bind(this));
Upvotes: 2