我刚刚开始使用require.js。我已经成功地包装了 jquery、一些插件和几个我自己的模块。我正在尝试与 Firebug(或 Google Chrome 的 JS 控制台)中的模块(或 jquery)进行交互,但我运气不佳。
从控制台访问这些模块的正确方法是什么?
我刚刚开始使用require.js。我已经成功地包装了 jquery、一些插件和几个我自己的模块。我正在尝试与 Firebug(或 Google Chrome 的 JS 控制台)中的模块(或 jquery)进行交互,但我运气不佳。
从控制台访问这些模块的正确方法是什么?
假设我们有返回一些方法的模块 /app/scripts/methodsModule.js:
define({
someMethod: function() {
// do stuff
},
anotherMethod: function() {
// do some more stuff
}
});
在我们的数据主文件 /app/scripts/main.js 我们有:
require(['methodsModule'], function(methods) {
methods.someMethod() // call someMethod
methods.anotherMethod() // call anotherMethod
})
一旦 requireJS 加载了我们的 data-main,我们就可以从 javascript 控制台命令行访问任何已经被 requireJS 加载的模块,如下所示:
>> methods = require('methodsModule'); // requireJS has module methodsModule stored
>> methods.someMethod() // call someMethod
>> methods.anotherMethod() // call anotherMethod
如果一个模块没有通过调用 require() 或 define() 加载,我们必须传递我们自己的回调,以便在模块加载后调用 require 函数:
>> myCB = function(methods) { methods.someMethod() }
>> require(['methodsModule'], myCB)
否则,requireJS 会抛出一个错误,提示模块尚未加载。
有一种不使用回调的方法。
如果您的模块在控制台或之前的应用程序中不需要,您可以先要求它:
require(['methodsModule']);
之后,您可以使用“动态”要求访问它:
require('methodsModule').someMethod();