Reputation: 20874
I am using RequireJS and Backbone and listening to a collection
's add
event using listenTo
. I cannot figure out how to reference this
as the instance of the view I am in, in this case GroupView
.
define([
'underscore',
'backbone',
'handlebars',
...
...
], function(_,Backbone,Handlebars,...){
...
...
var GroupsView = Backbone.View.extend({
el: "#current-item",
collection: Groups,
model: Group,
groupTemplate: Handlebars.compile(GroupTemplate),
events: {
"click #add-group" : "addGroupClicked",
},
initialize: function(){
this.listenTo(Groups,'add',this.addGroup,this);
},
addGroup: function(group){
//I want a reference to this instance of GroupsView here.
//if I use this... it references
//Uncaught TypeError: Object [object global] has no method 'groupTemplate'
console.log(this.groupTemplate);
//Uncaught TypeError: Object [object global] has no method 'redrawGroups'
--> console.log(this.redrawGroups);
},
redrawGroups: function(){
},
...
...
Upvotes: 0
Views: 97
Reputation: 35790
You have:
this.listenTo(Groups,'add',this.addGroup,this);
With Backbone's on
you can provide a 4th argument, as you have done, to set the context. However, that doesn't work with listenTo
; it only takes three arguments (this is because listenTo always sets the context to the listented-to object).
You should be able to get around this by creating a bound addGroup
like so:
this.listenTo(Groups,'add',_(this.addGroup).bind(this));
Alternatively you could simply bind the method to your class with:
_(this).bindAll('addGroup');
which would then let you do just:
this.listenTo(Groups,'add',this.addGroup);
Upvotes: 2