我正在使用RequireJS和Backbone,并使用collection监听addlistenTo事件。我无法弄清楚如何引用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(){

        },
    ...
    ...

最佳答案

你有:

 this.listenTo(Groups,'add',this.addGroup,this);


使用Backbone的on,您可以像提供的那样提供第4个参数来设置上下文。但是,这对listenTo不起作用;它只需要三个参数(这是因为listenTo始终将上下文设置为被侦听的对象)。

您应该可以通过创建绑定的addGroup来解决此问题,如下所示:

 this.listenTo(Groups,'add',_(this.addGroup).bind(this));


另外,您可以使用以下方法将方法绑定到您的类:

_(this).bindAll('addGroup');


然后,您可以这样做:

 this.listenTo(Groups,'add',this.addGroup);

09-18 10:09