如何正确使用Require.js
加载返回需要依赖项的构造函数的模块?
我的问题似乎是一个范围问题,我看到一些模块在返回的构造函数中可用,如“durandal / app”,我不知道它们的范围与我定义的模块有什么不同。
此示例已从Durandal Creating a Module docs
中修改define([**someothermodule**, "durandal/app"], function(**someothermodule**, app){
var backend = function(username, password){
this.username = username;
this.password = password;
someothermodule.whatever(); <--someothermodule is not defined
app.whatever(); <-- this is in scope
};
backend.prototype.getCustomers = function(){
//do some ajax and return a promise
};
return backend;
});
define([backend],function(backend){
return {
customers:ko.observableArray([]),
activate:function(){
var that = this;
var service = new backend('username', 'password');
return service.getCustomers().then(function(results){
that.customers(results);
});
}
};
});
Someothermodule:
define([], function(){
var whatever = function(){
alert("whatever");
};
return {
whatever: whatever
};
});
答案 0 :(得分:0)
索引有两个问题。 a)在使用define [backend]
而不是['backend']
时使用b)ko
而不定义它。两者都可能是复制/粘贴错误。
假设 someothermodule 与index.js位于同一目录中,就足以定义它了
define(['./someothermodule', ...], function( someothermodule, ... )
以下是完整的示例:
/*globals define*/
define(['./someothermodule', 'durandal/app', 'jquery'], function( someothermodule, app, $ ) {
"use strict";
var backend = function( username, password ) {
this.username = username;
this.password = password;
this.whatever = someothermodule.whatever();
app.trigger('whatever', this.whatever);
};
backend.prototype.getCustomers = function() {
//do some ajax and return a promise
return $.getJSON('app/so/19551060/fixtures/customer.json');
};
return backend;
});
/*globals define*/
define(function(){
"use strict";
var whatever = function(){
return 'whatever return value';
};
return {
whatever: whatever
};
});
/*globals define*/
define(['./backend', 'knockout'], function(backend, ko){
"use strict";
return {
customers:ko.observableArray([]),
activate:function(){
var that = this;
var service = new backend('username', 'password');
return service.getCustomers().then(function(results){
that.customers(results);
});
}
};
});