如何使用需要返回具有依赖项的构造函数

时间:2013-10-23 19:53:22

标签: requirejs durandal durandal-2.0

如何正确使用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
};

});

1 个答案:

答案 0 :(得分:0)

上面示例中的

索引有两个问题。 a)在使用define [backend]而不是['backend']时使用b)ko而不定义它。两者都可能是复制/粘贴错误。

假设 someothermodule 与index.js位于同一目录中,就足以定义它了

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

以下是完整的示例:

backend.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