1

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)

  });
},
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
ac360
  • 7,735
  • 13
  • 52
  • 91
  • 2
    See http://stackoverflow.com/questions/337878/var-self-this (and probably several other questions on SO) – tsiki Aug 17 '13 at 18:21

1 Answers1

2

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));
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43