2013-07-26 21 views
2

我有下面的代碼:如何執行我的回調函數是一個自定義的Dojo模塊?

define(["dojo/_base/declare"],function (declare) { 
    return declare("tamoio.Map", null, { 

    methodA: function(param){ 
     console.log(param); 
     this.methodB('xxx',function(){ 
      this.methodC(); //it didn't call! 
     }); 
    }, 

    methodB: function(text, callback){ 
     alert('do nothing: ' + text); 
     callback(); 
    }, 

    methodC: function(){ 
     alert('hello'); 
    } 

    }); 
}); 

當我運行我的應用程序收到messege:

Uncaught TypeError: Object [object global] has no method 'methodC' 

該怎麼辦。我祈求我的模塊中的內部方法?

我使用道場1.9.1

最好的問候,

雷南

+0

夥計們,我通過函數methodC作爲回調函數,然後另一個函數 – rbarbalho

回答

3

,因爲你的回調函數是在全球範圍內(窗口)執行您收到此錯誤,並且有沒有定義稱爲methodC的函數。你需要得到methodC在小部件的範圍內執行,並有這樣做的方法有兩種:

1)採取的JavaScript關閉的優勢:

methodA: function(param){ 
    console.log(param); 
    var self = this; // Create a reference to the widget's context. 
    this.methodB('xxx',function(){ 
    self.methodC(); // Use the widget scope in your anonymous function. 
    }); 
} 

2)充分利用的dojo/_base/lang模塊的hitch方法:

methodA: function(param){ 
    console.log(param); 
    this.methodB('xxx', lang.hitch(this, function(){ 
    this.methodC(); 
    })); 
} 

hitch方法返回將在所提供的上下文中執行的功能,在這種情況下,它是this(窗口小部件)。

+0

嗨,夥計,非常感謝\ o/!!! – rbarbalho

+0

沒問題!很高興我能夠提供幫助。 JavaScript範圍需要一些時間來習慣。 – Default

相關問題