2012-11-19 24 views
2

我這裏有一些代碼:有什麼處理「這個」不使更多的標準「即」參考「這個」

App.prototype.binds = function(){ 
    var that = this; 
    $('.postlist li').live('click', function(){ that.selectPost(this);}); 
} 

App.prototype.selectPost = function(){ 
    this.function(); 
} 

我創造「這個」是「」在的參考我的綁定函數,所以在我的selectPost(),我可以使用「this」來引用應用程序對象,而不是列表項。

有沒有更優雅/標準的解決方案,而不是使用「那個」?


的答案,我的代碼就變成了:

function App() { 
    this.selectPost = this.selectPost.bind(this); 
        //$.proxy(this.selectPost, this) in jQuery 
} 

App.prototype.binds = function(){ 
    $('.postlist li').live('click', this.selectPost); //Already bound in constructor 
} 

只是

在構造函數中:

App.prototype.binds = function(){ 
    $('.postlist li').live('click', $.proxy(this.selectPost, this)); 
} 

App.prototype.selectPost = function(e){ 
    this.function(); // function in App 

    var itemClicked = e.currentTarget; //or 
    var $itemClicked = $(e.currentTarget); 
} 
+0

* *表示標準。 (或* self *,或* $ this *) – ahren

回答

5

可以綁定在構造函數或只是時間的功能及時:

App.prototype.binds = function(){ 
    $('.postlist li').live('click', this.selectPost.bind(this)); 
            //$.proxy(this.selectPost, this) in jQuery 
} 

請注意,.bind僅在較新的瀏覽器中受支持,jQuery有$.proxy應該是首選。

我已經在jQuery中打開了一個已被接受的功能請求http://bugs.jquery.com/ticket/12031。當使用jQuery事件時,它會使這更容易。

請注意,有一個常見的誤解,e.target將與jQuery事件處理程序中的正常this相同。它實際上是e.currentTarget。所以現在this指的是實例而不是元素,你可以通過e.currentTarget得到elemet。