我显然缺少一些概念/理解,绝大多数是
javascript OO基础知识!
我喜欢使用RequireJS,现在我的网络应用程序看起来更像是一个结构化的应用程序,而不是一堆疯狂的代码.
我正在努力了解如何/如果可能的话.
我有一个模块作为基础数据服务模块,名为dataservice_base,如下所示:
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',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,callbacks) { return dataservice.ajaxRequest('delete',data) .done(callbacks.success) .fail(callbacks.error) }; // Public: Return public interface return { setRoute: setRoute,getAllEntities: getAllEntities,getEntitiesById: getEntitiesById,putEntity: putEntity,postEntity: postEntity,deleteEntity: deleteEntity }; });
正如您所看到的,我正在引用dataservices / dataservice,它实际上是核心AJAX调用机制(未显示,但实际上只是包装器中的基本jQuery ajax调用).
我想要做的是允许这个基础数据服务模块“实例化”如下(在另一个模块中 – 仅代码片段代码):
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_subjects
..当然,我正在努力为每个实例设置一个唯一的setRoute值,以便在模块中进一步使用..同时利用常见的调用(get,puts,posts等).
显然我在这里遗漏了一些东西……但任何有助于我回到路上的帮助都会非常感激!
亲切的问候,
大卫.
解决方法
我认为您只需要包含一次依赖项并使用
new关键字.可能您需要重构,以便常见功能在依赖模块中:
define(['dataservices/dataservice'],function (dataservice) { var dataservice_profile = new dataservice(); var dataservice_qualifications = new dataservice(); var dataservice_subjects = new dataservice(); // Set the service route(s) dataservice_profile.setRoute('/api/profile/'); dataservice_qualifications.setRoute('/api/qualification/'); dataservice_subjects.setRoute('/api/subject/'); // define needs to return something return { profile: dataservice_profile,qualifications: dataservice_qualifications,subjects: dataservice_subjects }; });