立即绑定javascript对象方法以进行事件处理

时间:2012-11-17 15:56:20

标签: javascript javascript-events binding

我想将事件处理函数用作javascript对象的一部分。我想将事件处理程序中的“this”绑定到它是方法的对象,因为事件处理程序中的“this”通常会自动分配给事件发生的对象。

这可以通过对发生绑定的对象使用init函数来完成(jsfiddle for tryout):

var myObject = {
    init:function(){
        this.downHandler = this.downHandler.bind(this);
    },
    downHandler:function(){
        alert(this.someInfo);
    },
    someInfo:"hi there"
}      
myObject.init();

我想避免这种情况:在其他地方重新定义它会降低代码的可维护性。所以我正在寻找一种能够在方法本身保持绑定过程的解决方案。

我已经尝试过立即执行功能,但是在立即执行时,“this”指向“window”对象(假设是浏览器上下文)。我的试验看起来像这样:

var myObject = {
//more code
    downHandler:(function(){
        alert(this.someInfo);
    }).bind(this), //does not work since at the point of immediate execution, the this is assigned to window
//more code
}      

你能想到一种在事件处理函数中保持绑定而不是在单独的init函数中的方法吗?

3 个答案:

答案 0 :(得分:2)

由于你已经加载了jQuery,请使用jQuery.proxy

var myObject = {
    downHandler: $.proxy(function(){
       alert(this.someInfo);
    }, this)
};

如果您安装了Underscore(我更喜欢这样的话),请使用_.bind

var myObject = {
    downHandler: _.bind(function(){
       alert(this.someInfo);
    }, this
};

MooTools可能也有类似的东西 - 我从未考虑过使用它。

答案 1 :(得分:0)

var myObject = {
    clickHandler: function() {
        alert(myObject.someInfo); 
        //returns undefined without execution of init-function
        //returns "hi there" if init ran. 
    },
    someInfo: "hi there"
}

$('#clickMe').on('click', myObject.clickHandler);

答案 2 :(得分:0)

在警报期间使用对象名称'myObject'而不是'this'。

var myObject = {
    downHandler:(function(){
        alert(myObject.someInfo);
    }).bind(this), 
  //when 'this' use it alert undefined
  //when 'myObject' use it alert "hi there"
   someInfo:"hi there" 
}   

我希望这会对你有所帮助。