【问题标题】:Access private function of a RequireJS module [duplicate]访问RequireJS模块的私有函数[重复]
【发布时间】:2013-09-05 12:22:55
【问题描述】:

我有这个模块:

define(function() {
   clickHandlerA = function() { ... }
   clickHandlerB = function() { ... }

   return {
     handle : function(param) {
        doSomething(param);
        var handler = 'clickHandler' + param;
     }
   }
}

现在,我需要以某种方式调用适当的点击处理程序。我试过了

if (typeof handler  == 'function') {
   handler.call();
}

我也试过了

if (handler in this) {
   handler();
}

但没有任何工作。有什么建议吗?

【问题讨论】:

  • 你不能从外部访问处理程序,你必须导出它。
  • @dystroy 如果我要转移 clickHandlerA 和 B 以返回我的模块的语句,我将如何调用它们并检查它们是否存在?

标签: javascript requirejs


【解决方案1】:

我知道你需要的是这个:

define(function() {
   var handlers = {
      A: function() { ... },
      B: function() { ... }
   };

   return {
     handle : function(param) {
        doSomething(param);
        return handlers[param];
     }
   }
}

所以你可以从外面做这个

 yourModule.handle('A')();

【讨论】:

  • 这是我一直在寻找的解决方案。
猜你喜欢
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多