将Plain Old JavaScript Object转换为Require.js模块

时间:2014-04-16 18:51:28

标签: javascript requirejs

我正在重构JavaScript应用程序以使用Require.js。到目前为止,我一直都很好,直到我有这个概念性的斗争。

在模块中,创建了许多新对象:

new Dealer(self.c, self.config, "Dealership", "2333 South Loop West, Houston, TX 77054", 6.07, "(713) 558-8100", "9am - 9pm", 0, "http://mikecalverttoyota.com/"),
new Dealer(self.c, self.config, "Dealership", "9400 Southwest Freeway, Houston, TX 77074", 8.89, "(713) 270-3900", "8:30am - 9pm", 1, "http://www.sterlingmccalltoyota.com/")

现在,这些创建得很好 - 另一个文件dealer.js具有对象定义:

function Dealer(c, config, name, address, distance, phone, hours, index, url) {
    var self = this;
    self.c = c;
    self.config = config;
    ...
}

从概念上讲,如何将Dealer对象转换为require.js模块,以便我可以在其他模块中使用它,然后在这些模块中实例化它的副本?

1 个答案:

答案 0 :(得分:5)

这是最简单的方法:

define(function () {
    function Dealer(c, config, name, address, distance, phone, hours, index, url) {
        var self = this;
        self.c = c;
        self.config = config;
        ...
    }

    return Dealer;
});

上面的代码可能位于名为dealer.js的文件中。然后在您使用它的模块中:

define(['dealer'], function (Dealer) {

    new Dealer(self.c, self.config, "Dealership", "2333 South Loop West, Houston, TX 77054", 6.07, "(713) 558-8100", "9am - 9pm", 0, "http://mikecalverttoyota.com/"),
    new Dealer(self.c, self.config, "Dealership", "9400 Southwest Freeway, Houston, TX 77074", 8.89, "(713) 270-3900", "8:30am - 9pm", 1, "http://www.sterlingmccalltoyota.com/")
});