【问题标题】:How to execute my callback function is a custom Dojo module?如何执行我的回调函数是自定义 Dojo 模块?
【发布时间】:2013-07-27 03:18:25
【问题描述】:

我有以下代码:

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');
     }

   });
});

当我运行我的应用程序时,我收到了消息:

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

如何在我的模块中调用内部方法?

我正在使用 Dojo 1.9.1

最好的问候,

仁南

【问题讨论】:

  • 伙计们,我将函数 methodC 作为回调函数传递,然后是另一个函数

标签: javascript function dojo callback scope


【解决方案1】:

您收到此错误是因为您的回调函数正在全局范围(窗口)中执行,并且没有定义名为 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(小部件)。

【讨论】:

  • 没问题!很高兴我能提供帮助。 JavaScript 作用域需要一些时间来适应。
猜你喜欢
  • 1970-01-01
  • 2016-01-21
  • 2012-09-20
  • 1970-01-01
  • 2023-03-12
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多