2010-06-10 21 views
0

下面的代碼不工作,我憑直覺就想到:的jQuery/JavaScript事件 - 原型事件處理

function MyObject(input) { 
    input.change(this._foo); 
    this.X = undefined; 
} 

MyObject.prototype._foo = function() { 
    alert("This code is never called"); 
    // but if it did 
    this.X = true; 
} 

var test_input = $("input#xyz"); // a random, existing input 

var m = MyObject(test_input); // attach handler (or try to) 

test_input.change(); // trigger event 

alert(m.X); // undefined 

我期望_foo()將被稱爲(和,如果沒發生,那在_foo()this變量是爲MyObject的一個實例。

有誰知道爲什麼這不適合傳遞對象與事件處理工作,以及任何其他模式?

感謝您閱讀ING。

布賴恩

+0

在jQuery中有一些附加事件('bind()','live()')和觸發事件('trigger()')的方法。我不確定你在這裏得到什麼。另外,在我看來,如果你想調用一個對象方法,你需要調用它像'this._foo()'而不是'this._foo',否則你正在做任務。這完全有可能我誤解了你。 – artlung 2010-06-10 22:12:04

+0

可能重複的[如何訪問正確的\'this \'/ context在回調?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside -a-callback) – Bergi 2014-02-27 18:59:53

+0

謝謝Bergi。在這個關閉的三年之後,被引用的問題被問到了,那麼重複會不會真的走向另一個方向?將這個問題標記爲「已經回答」了三年後出現的問題是錯誤的,並且似乎具有誤導性。這個問題不是這個問題的重複嗎? – 2014-02-27 19:18:52

回答

4

正如Kenny指出你錯過了new。您還需要確保在this_fooMyObject實例
一種方式做到這一點: -

function MyObject(input) { 
    var _this = this; 
    input.change(function() { 
     // explicitly set the `this` in _foo to `_this` 
     _this._foo.call(_this); 
    }); 
    this.X = undefined; 
} 

MyObject.prototype._foo = function(event) { 
    alert("This is called"); 
    // and 'this', being 'm', has X set to true 
    this.X = true; 
    // the textbox must be accessed by 'event.target' not 'this' if you need it 
} 

var test_input = jQuery("input#xyz"); // a random, existing input 

var m = new MyObject(test_input); // attach handler (or try to) 

test_input.change(); // trigger event 

alert(m.X); // true 

P.S 你無法避免離開它使用new操作符! :)

2

使用JavaScript創建對象,請使用new

var m = new MyObject(test_input); // attach handler (or try to) 
+0

正如道格拉斯克羅克福德所建議的,我一直在試圖避免使用'new',但是您至少在代碼中指出這一個錯誤是正確的。 :) – 2010-06-10 21:34:38

+0

@Brian:如果不使用'new','MyObject'內的'this'指向'window',而不是'MyObject'的「實例」。我把「instance」放在引號內,因爲不想使用'new',你永遠不會創建任何東西的實例。 – Matt 2010-06-10 22:10:59

1

這個問題現在有點老了,但還有另一種解決方案。您的問題與上文提到的一樣,您錯過了「新建」,並且事件處理程序中的「this」引用始終是觸發事件的元素,而不是處理事件的對象。

由於您使用的是JQuery,因此有一種簡單的方法可以按照您的要求進行操作。使用JQuery.proxy method設置事件處理程序的上下文,以便將對象用作「this」。在你的榜樣,你只需要更改線路

input.change(this._foo); 

input.change(jQuery.proxy(this, "_foo")); 

給一個嘗試,如果你遇到這個問題與jQuery一次。