2013-07-26 27 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

相关问题