我明显错过了一些概念/理解和绝对的JavaScript OO基础知识!我可以拥有RequireJS模块的多个实例吗?
我喜欢使用RequireJS,现在我的web应用程序看起来更像是一个结构化的应用程序,而不是一堆疯狂的代码。
我只是努力了解如何/如果以下是可能的。
我有充当所谓dataservice_base作为基础DataService的模块,一个模块如下:
define(['dataservices/dataservice'], function (dataservice) {
// Private: Route URL
this.route = '/api/route-not-set/';
var setRoute = function (setRoute) {
this.route = setRoute;
return;
}
// Private: Return route with/without id
var routeUrl = function (route, id) {
console.log('** Setting route to: ' + route);
return route + (id || "")
}
// Private: Returns all entities for given route
getAllEntities = function (callbacks) {
return dataservice.ajaxRequest('get', routeUrl())
.done(callbacks.success)
.fail(callbacks.error)
};
getEntitiesById = function (id, callbacks) {
return dataservice.ajaxRequest('get', routeUrl(this.route, id))
.done(callbacks.success)
.fail(callbacks.error)
};
putEntity = function (id, data, callbacks) {
return dataservice.ajaxRequest('put', routeUrl(this.route, id), data)
.done(callbacks.success)
.fail(callbacks.error)
};
postEntity = function (data, callbacks) {
return dataservice.ajaxRequest('post', routeUrl(this.route), data)
.done(callbacks.success)
.fail(callbacks.error)
};
deleteEntity = function (id, data, callbacks) {
return dataservice.ajaxRequest('delete', routeUrl(this.route, id), data)
.done(callbacks.success)
.fail(callbacks.error)
};
// Public: Return public interface
return {
setRoute: setRoute,
getAllEntities: getAllEntities,
getEntitiesById: getEntitiesById,
putEntity: putEntity,
postEntity: postEntity,
deleteEntity: deleteEntity
};
});
正如你所看到的,我引用DataService的/ DataService的,这实际上是核心AJAX调用机制(没有显示,但真的只是基本的jQuery ajax调用包装)。
我所试图做的是让此基础DataService的模块是“实例化”如下(在另一个模块 - 唯一的代码片段):
define(['dataservices/dataservice_base', 'dataservices/dataservice_base', 'dataservices/dataservice_base'], function (dataservice_profile, dataservice_qualifications, dataservice_subjects) {
// Set the service route(s)
dataservice_profile.setRoute('/api/profile/');
dataservice_qualifications.setRoute('/api/qualification/');
dataservice_subjects.setRoute('/api/subject/');
正如你所看到的,我想包括(以上定义)相同dataservice_base 3倍,但在功能的引用,我想通过一个名为瓦尔指每个实例,即:
dataservice_profile,dataservice_qualifications,dataservice_subjects
..当然,我试图能够设置一个独特的setRoute价值为每个这些实例进一步在模块中使用..同时利用普通的电话(get,puts,posts等)。
显然我错过了这里的一些东西..但任何帮助指出我回到路上将非常感激地收到!
亲切的问候, 大卫。
我一直在为这个概念而努力。这个答案很清楚! ......我想这里的关键是理解RequireJS总是返回一个模块的同一个实例,不管你“需要”多少次。但是,如果您的模块返回构造函数而不是静态对象,则可以使用客户端模块中的new关键字从构造函数创建实例。 RequireJS每次都返回相同的构造函数,但这就是我们想要的,因为它是一个模板,一个类。客户端模块的工作是创建该类的实例。 –
“”“我想这里的关键是要了解RequireJS总是返回一个模块的同一个实例,无论你”需要“多少次。”“”“ 差不多。它确实缓存了第一个需要的实例,但只有在相同的确切路径上具有相同的确切模块。 这意味着如果你在2个不同的路径(对于你的应用的不同部分)有相同的lib“xxx”,如:app/modules/foo/xxx和app/modules/bar/xxx,不同的实例。这可能发生,例如如果每个模块都有不同的package.json,并且它们要求相同的库。 – Hejazzman