我如何使需求多态加载模块

How can I make requirejs polymorphically load a module?

本文关键字:加载 模块 多态 需求 何使      更新时间:2023-09-26

我目前正在使用Cordova 3.4.0, Requirejs和Backbone开发一个单页应用程序。在将我的应用程序从iPhone移植到iPad的过程中,我需要改变一些视图中的一些功能,而保持其他部分不变。

为了使更改最小化,我的解决方案是为每个需要更改的视图创建新对象,继承原始视图的所有属性并只覆盖必要的功能。

要做到这一点,我需要配置Requirejs,以便在iPad中,如果我需要,例如,'user/view/edit-profile.js',它将检查是否有'user/iPad/view/edit-profile.js'文件,如果有,则需要它,否则需要'user/view/edit-profile.js'

我试过i18n,但它不适合这种情况。我想出了一个想法,为完成任务的需求创建一个新的插件。

有人对我的问题有什么建议吗?

顺便说一句,因为所需的文件会根据平台动态变化。我称之为多态性。

您可以使用路径回退:

paths: {
    "user/view/edit-profile": ["user/ipad/view/edit-profile", "user/view/edit-profile"]
}

以上将使RequireJS首先尝试加载ipad变体。如果在开发应用程序时,逻辑过于复杂,无法进行回退,则可以使用errbacks:

function onload(module) {
    // Whatever you want to do...
};
require([module_a], onload, function (err) {
    require([module_b], onload);
});

上面的代码将尝试从module_a加载模块,然后从module_b加载。我使用这种代码来加载具有在运行时计算的名称的模块。

因为每个模块都是一个骨干视图,我想出了一个解决方案,这将覆盖骨干视图的扩展功能,以返回修改的对象取决于ipad, iphone或android依赖的存在。

解决方案将要求,如果一个基视图有iPad版本,它必须在dependencies声明iPad版本,扩展函数将通过iPad视图扩展现有视图,以便iPad视图可以继承基视图的所有属性并只覆盖必要的功能。

我将视图命名为PolyplatformView。每个视图都需要声明它的ID,例如:user/view/edit-profile

Backbone.PolyplatformView = Backbone.View.extend({
});
Backbone.PolyplatformView.extend = function() {
    if(arguments[0].moduleId) {
        var extendPropsPath = arguments[0].moduleId.replace('/', '/' + constants.platform_name + '/'); 
        // turn user/view/edit-profile -> user/ipad/view/edit-profile
        if(require.defined(extendPropsPath)) {
            _.extend(arguments[0], require(extendPropsPath));
        }
    } else {
        console.warn('No module Id in polyplatform view -> cannot extend its parent');
    }
    var extended = Backbone.View.extend.apply(this, arguments);
    return extended;
}