2011-06-10 46 views
2

我有一個庫提供的函數,經過一些處理後運行回調。在回調中訪問父對象和調用對象?

在回調中,我想訪問其方法啓動回調的父對象 - 請參見下文。

class MaskMaker 
    addMaskedImage: (imagefile, texturefile, canvasid) -> 
    $('<img src="'+imagefile+'">').load -> 
     console.log('Id like to call another MaskMaker method with @width as a parameter') 

顯然=>會給我訪問父對象,因爲這/ @, - >會給我訪問元件觸發回調因爲這/ @。但是最好的方法是做什麼,例如,所以我可以調用MaskMaker的一個直接方法,將圖像寬度作爲參數?我需要一個=這個黑客還是有更好的?

謝謝!

回答

3

但是,什麼是做兩件事最巧妙的方法,例如,所以我可以打電話給MaskMaker與圖像的直接方法寬度作爲參數?

你不能同時選擇(明顯),所以會去與任何=> + event.target

$('<img src="'+imagefile+'">').load (ev) => @method ev.target.width 

或好醇」

that = this 
$('<img src="'+imagefile+'">').load -> that.method @width 

參見:https://github.com/jashkenas/coffee-script/issues/1230

+0

第一種解決方案正是我在尋找的東西 - 不需要'that'或'self'攻擊.JQuery文檔提到你可以明確地傳遞對象 - http ://api.jquery.com/load-event - 但我錯過了這個,非常感謝。 – mikemaccana 2011-06-26 12:06:17

2

如果我完全理解你的代碼結構,你可以添加一個變量來保存對MaskMaker實例的引用。由於範圍的限制,您將能夠看到更多鏈條。

class MaskMaker 
    var self = this; 
    addMaskedImage: (imagefile, texturefile, canvasid) -> 
    $('<img src="'+imagefile+'">').load -> 
     console.log('Id like to call another MaskMaker method with @width as a parameter') 
     //self references MaskMaker now, so you can call self.addMaskedImage for example 
+0

工作正常(用'self = @'取代'var self = this'')我想知道(我自己編輯過這個問題要說)有沒有內置到coffeescript中的東西可以避免必須做這種東西,但我不懷疑:你可能會有很多函數在你想要引用的對象下面,而JS/CS無法知道你想要調用哪一個函數。 – mikemaccana 2011-06-10 18:12:46

+0

我不是如果是Coffeescript,但Javascript不會。 – Robert 2011-06-10 18:17:35

0

在MaskMaker的範圍內定義和綁定你的回調:

class MaskMaker 
    afterAdd => console.log('Id like to call another MaskMaker method with @width as a parameter') 
    addMaskedImage: (imagefile, texturefile, canvasid) -> 
     $('<img src="'+imagefile+'">').load -> afterAdd() 

請注意,我使用的脂肪箭頭語法=>綁定存儲在afterAdd到MaskMaker功能。

+0

這不起作用。首先,你的意思是'afterAdd = => ...',但更重要的是'afterAdd'綁定到'MaskMaker'構造函數,而不是實例。 – lawnsea 2011-06-12 19:02:34

+0

NM,你是故意綁定到構造函數的。我的錯。 – lawnsea 2011-06-12 19:05:33