1

您如何正确使用Require.js来加载返回具有需要依赖项的构造函数的模块?

我的问题似乎是范围问题,我已经看到返回的构造函数中可用的一些模块,如“durandal/app”,我看不出它们的范围与我定义的模块有何不同。

这个例子是从 Durandal 创建一个模块文档修改的

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;

});

定义([后端],函数(后端){

return {
    customers:ko.observableArray([]),
    activate:function(){
        var that = this;
        var service = new backend('username', 'password');

        return service.getCustomers().then(function(results){
            that.customers(results);
        });
    }
};

});

其他模块:

define([], function(){

var whatever = function(){
    alert("whatever");
};

return {
    whatever: whatever
};

});

4

1 回答 1

0

上面示例中的索引有两个问题。a) in define[backend]用于代替,['backend']b)ko用于未定义。两者都可能复制/粘贴错误。

假设someothermodule与 index.js 位于同一目录中,将其定义为

define(['./someothermodule', ...], function( someothermodule, ... ) 

这是完整的示例:

后端.js

/*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;
});

someothermodule.js

/*globals define*/
define(function(){
    "use strict";
    var whatever = function(){
        return 'whatever return value';
    };

    return {
        whatever: whatever
    };
});

index.js

/*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);
            });
        }
    };
});

现场版可在:http ://dfiddle.github.io/dFiddle-2.0/#so/19551060

于 2013-10-24T07:56:07.207 回答