2013-02-18 133 views
2

我使用Class.js來創建類。如何從回調函數中調用正確的類上下文

從一個回調函數invocked時,我沒有得到一個方法內正確的上下文

我的代碼是

WordCloud = MyClass.extend({ 
    init: function(data) { 
     var me = this; 
     (......).on("onComplete", this.draw); 
    }, 
    show: function(word) { 
     alert(word) 
    }, 
    draw : function(words){ 
     console.debug(this); // prints element that triggred `onComplete` action 
     console.debug(words); // "Hi" 
     console.debug(me); // me is not defined 
     me.show(words) // Need to call this method 
    } 
}); 

問題是,當完成一個動作draw方法解僱,但裏面draw方法this不是實際的class實例,而是觸發回調操作的元素。

我不能通過exta參數,而調用this.draw,因爲它是一個回調函數而onComplete只有一個參數。

如何從draw調用show方法?

回答

3

如果你沒有支持Internet Explorer 8或更低,則可以使用bind()

init: function(data) { 
    var me = this; 
    (......).on("onComplete", this.draw.bind(this)); 
} 

否則,如果你已經使用jQuery,您可以利用$.proxy(),它的工作方式相同:

init: function(data) { 
    var me = this; 
    (......).on("onComplete", $.proxy(this.draw, this)); 
} 
1

我對這些情況使用了輔助函數。

function hitch(obj, func) { 
    return function() { 
     return obj[func].apply(obj, arguments || []) 
    }; 
} 

要調用它,你會用hitch(this, 'draw');代替this.draw

或者使它更簡單,你可以簡化版本添加到您的基類

function hitch(func) { 
    var that = this; 
    return function() { 
     return that[func].apply(that, arguments || []) 
    }; 
} 

並調用this.hitch('draw');

相關問題