javascript - 使用 Durandal 时查看模型继承

标签 javascript single-page-application durandal

我正在使用 Durandal 构建一个应用程序,并且需要跨 View 模型共享一些功能。

我要构建 5 个屏幕,它们几乎都是相同的屏幕,除了在激活函数中它们将调用不同的 api 端点,但否则 View 和 View 模型将是相同的。

是否应该遵循某种模式来正确构建此结构以促进代码重用?

最佳答案

如果 View 和 View 模型除了调用不同的 api 操作之外都是相同的,那么只接受一个参数作为路由的一部分怎么样?然后在activate函数中,就可以开启参数了。可以指定路由值,以便您的 url 相关,例如 [ http://site/page/subtype] ,其中子类型是参数(而不是使用数值)

关于继承,根据您需要的功能,有很多方法可以进行 JavaScript 继承,这可能会有点令人困惑。 Base2 和 Prototype 等库提供了一些功能齐全的继承模型。 John Resig also has an inheritance model我已经成功使用了。

总的来说,当涉及到 JS 继承时,我更喜欢坚持使用更简单的解决方案。如果您需要几乎全套的继承功能,那么这些库是值得考虑的。如果您只真正关心从基类访问一组属性和函数,则只需将 View 模型定义为函数,然后将函数的原型(prototype)替换为所需的基类即可。引用Mozilla's Developer Docs有关继承的详细信息。

这是一个示例:

 //viewModelBase
define(function (require) {
    "use strict";

    function _ctor() {

        var baseProperty = "Hello from base";
        function baseFunction() {
            console.log("Hello from base function");
        }
        //exports
        this.baseProperty = baseProperty;
        this.baseFunction = baseFunction;
    };

    //return an instance of the view model (singleton)
    return new _ctor();
});

//view model that inherits from viewModelBase
define(function (require) {
    "use strict";

    function _ctor() {

        var property1 = "my property value";
        function activate() {
            //add start up logic here, and return true, false, or a promise()
            return true;
        }
        //exports
        this.activate = activate;
        this.property1 = property1;
    };

    //set the "base"
    var _base = require("viewModelBase");
    _ctor.prototype = _base;
    _ctor.prototype.constructor = _ctor;

    //return an instance of the view model (singleton)
    return new _ctor();
});

请记住,这个示例的所有结果实际上都是单例(即,无论您 require() 多少次,您都只会获得相同的实例)

如果你想要一个 transient (非单例),只需返回 _ctor 即可。然后,您需要在 require() 之后实例化一个新实例。

还要注意的是,一般来说,函数应该在原型(prototype)上定义,而不是在构造函数本身内定义。请参阅this link for more information on why 。由于此示例仅生成一个实例,因此这是一个有争议的问题,因此函数位于构造函数内部,以提高可读性以及访问私有(private)变量和函数的能力。

关于javascript - 使用 Durandal 时查看模型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634111/

相关文章:

javascript - Breeze 是否消除了单页应用程序中对 DTO 的需求?

javascript - Durandal 模态回调

javascript - DurandalJs : A generic solution to put focus to the first input element on the composed view

javascript - 检测页面退出时 PrimeFaces 中 UI 组件的客户端更改?

javascript - 如何检查字符串是否与带星号的模式匹配

vue.js - Vue SPA - PhantomJS 成功运行,但 Fetch As Google 显示空白

javascript - Durandal showMessage 无法识别断线

javascript - 切换 Google map 标记

javascript - 将包含单个反斜杠的 Javascript 字符串拆分为两个字符串

javascript - 在单页应用程序中合并 HTML 文件