[英]Reference the containing backbone view from an event callback?
I am using RequireJS and Backbone and listening to a collection
's add
event using listenTo
. 我正在使用RequireJS和Backbone并使用listenTo
监听collection
的add
事件。 I cannot figure out how to reference this
as the instance of the view I am in, in this case GroupView
. 我无法弄清楚如何引用this
作为我所在的视图的实例,在本例中为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(){
},
...
...
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. 使用Backbone on
您可以提供第4个参数,就像您所做的那样,设置上下文。 However, that doesn't work with listenTo
; 但是,这不适用于listenTo
; it only takes three arguments (this is because listenTo always sets the context to the listented-to object). 它只需要三个参数(这是因为listenTo总是将上下文设置为listened-to对象)。
You should be able to get around this by creating a bound addGroup
like so: 您应该能够通过创建绑定的addGroup
来解决这个问题:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.