0

我有这个基本代码:

app.Modules.myModule = {
    init: function(){
        this.bindEvents();
    },

    bindEvents: function(){
        app.Events.on('user:added', this.userAdded.call(this));
        this.username = $('#username');
    },

    userAdded: function(event, params){
        console.log(params);
        this.username.text(params.username);
    }
};

现在我遇到的问题是,如果我按原样调用 this.userAdded,则 params 不会传递给 userAdded 函数。如果我不使用“调用”而只是在 userAdded 函数中执行 this.userAdded,那么“this”的上下文是 jQuery 事件,而不是像我需要的那样的“app.Modules.myModule”。

所以我的问题是,如何将 userAdded 函数中的“this”上下文保留到对象本身(myModule)并能够将其传递给 params 参数?

4

1 回答 1

1

如果将模块定义为函数,则可以在实例化时将上下文设置为变量。例如:

app.Modules.myModule = function(){

    var context = this;
    context.init = function(){
        context.bindEvents();
    };

    context.bindEvents = function(){
        app.Events.on('user:added', context.userAdded);
        context.username = $('#username');
    };

    context.userAdded = function(event, params){
        console.log(params);
        context.username.text(params.username);
    } ;       
};

var module = new app.Modules.myModule();

上下文变量现在将引用对象的上下文,并且可以在函数中使用。确保在初始化对象时使用“new”关键字。

于 2013-01-08T23:14:49.017 回答