Rad*_*adu 5 javascript requirejs
我正在定义一个模块Foo
,我在另一个模块中实例化它Bar
.我的第三个模块Other
,我想这与相同情况下提供Foo
的是Bar
创建和修改.
define('Foo', [], function() {
var test = function() {
this.foo = 'foo';
};
return test;
});
define('Bar', ['Foo'], function(Foo) {
Foo = new Foo();
Foo.bar = 'bar';
console.log('From bar', Foo);
});
define('Other', ['Foo'], function(Foo) {
console.log('From the other', Foo);
});
require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
console.log('Bringing it all together');
});
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/radu/Zhyx9/
没有要求,我会做的事情如下:
App = {};
App.Foo = function() {
this.foo = 'foo';
}
App.Bar = function() {
App.Foo = new App.Foo();
App.Foo.bar = 'bar';
console.log('From bar', App.Foo);
}
App.Other = function() {
console.log('From other', App.Foo);
}
App.Bar();
App.Other();
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/radu/eqxaA/
我知道我必须在这里遗漏一些东西,因为这是我在requirejs中的第一次尝试,可能存在某种误解.这个例子可能看起来很人为但我在使用Backbone和RequireJS的项目中遇到了类似的问题. .
我将此作为对其中一个答案的评论发布,但我知道我可以分享这样一个实例:
define('Foo', [], function() {
var test = function() {
this.foo = 'foo';
};
return new test();
});
define('Bar', ['Foo'], function(Foo) {
Foo.bar = 'bar';
console.log('From bar', Foo);
});
define('Other', ['Foo'], function(Foo) {
Foo.other = 'other';
console.log('From the other', Foo);
});
require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
console.log('Bringing it all together');
});
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/radu/XEL6S/
然而,我一开始没有这样做的原因是模块Foo
无法实例化自身,因为它需要 DOM 准备好。然而,作为 RequireJS 的新手,我不知道这种功能是内置于. 换句话说,要共享Foo
上面指定的模块实例,请在其定义中实例化并添加domReady
requireJS 文档中指定的模块。
归档时间: |
|
查看次数: |
4370 次 |
最近记录: |