从事件回调中引用包含主干视图

Reference the containing backbone view from an event callback?

本文关键字:包含主 视图 引用 事件 回调      更新时间:2023-10-20

我使用RequireJS和Backbone,并使用listenTo侦听collectionadd事件。我不知道如何引用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,您可以提供第四个参数来设置上下文,正如您所做的那样。然而,这对listenTo不起作用;它只需要三个参数(这是因为listenTo总是将上下文设置为listented to对象)。

你应该能够通过创建一个绑定的addGroup来绕过这个问题,比如:

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

或者,您可以简单地使用将方法绑定到您的类

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

然后让你做:

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