2010-05-03 89 views
1
this 
Application.EventManager.on('Click', function(args) { // event listener, args is JSON 
    TestAction.getContents(args.node.id, function(result, e) { 
     console.log(result); 
     this.add({ 
      title: args.node.id, 
      html: result 
     }).show(); 
    }); 
}); 

我真的作用域和匿名函數掙扎......我想this(1號線)是相同的對象this(5號線)... .call().apply()似乎是正確的想法,但我不想觸發事件...只是改變它的範圍......JS匿名範圍

對於一些情況下... this有問題是一個TabContainer和TestAction是一個返回內容的RPC ...

謝謝....

回答

2

你需要的是對被設置爲this外面範圍內定義的變量:

var that = this; 
Application.EventManager.on('Click', function(args) { // event listener, args is JSON 
    TestAction.getContents(args.node.id, function(result, e) { 
     console.log(result); 
     that.add({ 
      title: args.node.id, 
      html: result 
     }).show(); 
    }); 
}); 

感謝關閉,你可以這樣做(錯了,那),甚至裏面的函數。

+0

精美簡單......我已經浪費了太多的時間... – Simon 2010-05-03 23:00:24

+0

請參閱下面的@bmoeskau答案以獲得更美妙的答案。 – Upperstage 2010-05-04 12:42:33

2

是的,@ Joey的答案在通用的JS代碼中起作用。但是,由於您根據您的標籤使用了Ext JS,因此我會指出適當的方法是在適當的範圍內調用事件回調函數,以便Ext爲您處理傳遞和設置範圍。例如,分機的方法是(假設你的應用程序類使用EXT標準on()功能):這個......非常感謝

Application.EventManager.on('Click', function(args) { // event listener, args is JSON 
    TestAction.getContents(args.node.id, function(result, e) { 
     console.log(result); 
     this.add({ 
      title: args.node.id, 
      html: result 
     }).show(); 
    }); 
}, this); // 3rd arg to .on() is scope! 
+0

更好...讓我嘗試並稍後實現... – Simon 2010-05-04 11:19:47

+0

我認爲你必須將'this'添加到'TestAction.getContents'內部方法調用的範圍內(這似乎是一個ExtDirect調用)。 – 2010-05-04 12:52:04