You're binding your event handler using bind
(AKA on
):
this.collection.bind('add', this.modeladded);
But, as usual with JavaScript, the value of this
inside a function depends on how the function is called, not how it is defined (ignoring bound functions of course). You're not specifying a specific this
for your function anywhere so you're not getting any particular this
when it is called. If you give bind
the third context argument:
this.collection.bind('add', this.modeladded, this);
// ------------------------------------------^^^^
then Backbone will call modeladded
with the specific this
and you'll find that this
inside modeladded
will be your view.
You could also use _.bind
, Function.prototype.bind
, or $.proxy
to produce a bound version of your callback:
this.collection.bind('add', _(this.modeladded).bind(this));
this.collection.bind('add', this.modeladded.bind(this));
this.collection.bind('add', $.proxy(this.modeladded, this));
All of those produce new functions so you won't be able to unbind
them without stashing the bound functions somewhere. You'll usually avoid using these when you have the option to specify the context (AKA this
) explicitly.
There's also listenTo
:
listenTo
object.listenTo(other, event, callback)
Tell an object to listen to a particular event on an other object. The advantage of using this form, instead of
other.on(event, callback, object)
, is that listenTo allows the object to keep track of the events, and they can be removed all at once later on. The callback will always be called with object as context.
So you can (and should) say this:
this.listenTo(this.collection, 'add', this.modeladded);
That will take care of giving you the desired this
and makes it easier to clean up your event handlers when you're done with them. Similarly for the other event handlers you're using.