【问题标题】:Appcelerator and CommonJS modules (caching and circular references)Appcelerator 和 CommonJS 模块(缓存和循环引用)
【发布时间】:2012-06-07 05:55:21
【问题描述】:

事情是这样的:

我正在使用 CommonJS 方法使我的移动 (iPhone/Android) 应用程序模块化。那里并不奇怪。但有一件事我就是想不通。

CommonJS 让我可以创建 STATIC 私有变量,这让我可以轻松创建单例。我认为这至少是因为获取require()d 的文件的内容只读取一次,然后每次都返回导出对象(仅初始化一次)。

但是当我创建如下所示的循环引用时,每次都会执行包含模块内的代码。

等等…… 有趣的是,当我写这个问题时,我突然意识到在下一个开始之前对require() 的调用都没有完成(因此堆栈溢出如下所示)。

对我是否走上正轨有任何想法吗?这里已经过了凌晨 5 点,所以就我而言,所有的赌注都已经结束了:D。

示例:

看这段代码,它定义了一个单例:

/* Singleton.js */

exports.getSingleton = getSingleton;

function getSingleton(name) {
  if (!instance) {
    instance = new Thing(name);
  }

  return instance;
}

function Thing(name) {
  this.name = name;
}

var instance;

require()这个文件是这样的:

var theFirstThing = require('Singleton').getSingleton('first');
Ti.API.info('first: ' + theFirstThing.name)

var possiblyAnotherOtherThing = require('Singleton').getSingleton('second');
Ti.API.info('second: ' + possiblyAnotherOtherThing.name);

输出是:

[DEBUG] loading: /path/to/sim/MyApp.app/app.js, resource: app_js
[DEBUG] loading: /path/to/sim/MyApp.app/Singleton.js, resource: Singleton_js
[INFO] first: first
[INFO] second: first

为什么像下面这样的循环引用不起作用? (我自己可能已经回答了这个问题,如果你愿意,可以评论/回答)。

app.js

require('Banana');

Pinapple.js

require('Banana');

Banana.js

require('Pineapple');

因为输出是这样的:

[DEBUG] loading: /path/to/simulator/MyApp.app/app.js, resource: app_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js

/* etcetera (total of 15 times back and forth) */

[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Banana.js, resource: Banana_js
[DEBUG] loading: /path/to/simulator/MyApp.app/Pineapple.js, resource: Pineapple_js
[ERROR] Script Error = Maximum call stack size exceeded. (unknown file)

【问题讨论】:

    标签: titanium appcelerator circular-reference commonjs


    【解决方案1】:

    我也在 Appcelerator Titanium 中使用 CommonJS 模块来构建移动应用程序。我为解决循环依赖问题所做的是:如果 A 和 B 是 2 个循环依赖模块,则在 B 中 require(A),反之亦然就在你真正需要使用它之前 .就我而言,仅当单击某个按钮时,我才需要在 B 中使用 A,因此我在按钮的单击事件侦听器中的 B 中放置了一个 require(A)。希望对您有所帮助。

    【讨论】:

    • 非常感谢它节省了很多时间。
    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 2014-08-28
    • 2010-10-03
    • 1970-01-01
    • 2017-05-13
    • 2011-11-04
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多