簡體   English   中英

立即綁定用於事件處理的 Javascript 對象方法

[英]Immediate binding of Javascript object-method for event handling

我想使用事件處理函數作為 Javascript 對象的一部分。 我想將事件處理程序中的“this”綁定到它是其方法的對象,因為事件處理程序中的“this”通常會自動分配給事件發生的對象。

這可以通過對發生綁定的對象使用 init 函數來完成(用於 tryout 的 jsfiddle ):

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
}      

你能想出一種方法來將綁定保留在事件處理函數中,而不是在單獨的初始化函數中嗎?

因為你已經加載了 jQuery,所以使用jQuery.proxy

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

如果你安裝了Underscore (我更喜歡這樣的東西),使用_.bind

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

MooTools 可能也有類似的東西——我從來沒有考慮過使用它。

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);

在警報期間使用對象名稱“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" 
}   

我希望這能幫到您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM