简体   繁体   English

Knockout ViewModel基类,Javascript继承

[英]Knockout ViewModel base class, Javascript inheritance

I have been using Knockout.js for a lot of projects lately, and I am writing a lot of repetitive code. 我最近一直在为很多项目使用Knockout.js,我正在编写大量重复的代码。 I would like to be able to define a BaseViewModel class and have my page-specific ViewModels inherit from it. 我希望能够定义一个BaseViewModel类,并让我的页面特定的ViewModel继承它。 I am a bit confused about how to do this is Javascript. 我有点困惑,如何做到这一点是Javascript。 Here is my basic BaseViewModel : 这是我的基本BaseViewModel

(function (ko, undefined) {
    ko.BaseViewModel = function () {
        var self = this;
        self.items = ko.observable([]);
        self.newItem = {};
        self.dirtyItems = ko.computed(function () {
            return self.items().filter(function (item) {
                return item.dirtyFlag.isDirty();
            });
        });
        self.isDirty = ko.computed(function () {
            return self.dirtyItems().length > 0;
        });
        self.load = function () { }
    };
}(ko));

I would like to be able to list signatures for methods like load in the BaseViewModel and then give them definitions in the inheriting ViewModel. 我希望能够列出BaseViewModel load方法的签名,然后在继承的ViewModel中为它们提供定义。 Is any of this possible? 这有可能吗? I have found a few solutions online but they all rely on defining functions/classes to make the inheritance work. 我在网上找到了一些解决方案,但它们都依赖于定义函数/类来使继承工作。

Since your BaseViewModel is just adding all of the properties/methods to this (and not using prototype) then it is pretty easy: 由于您的BaseViewModel只是将所有属性/方法添加this (并且不使用原型),因此它非常简单:

In your new view models, just call BaseViewModel : 在新的视图模型中,只需调用BaseViewModel

var MyVM = function () {
    var self = this;
    ko.BaseViewModel.call(self);

    self.somethingElse = ko.observable();
    self.itemCount = ko.computed(function() { return self.items().length; });
    self.items([1, 2, 3]); 
};


// ...
var vm = new MyVM();

Javascript inheritance is done in two pieces. Javascript继承分为两部分。 The first is in the constructor, and the second is on the prototype (which you aren't using, so you could skip). 第一个是构造函数,第二个是原型(你没有使用,所以你可以跳过)。

var ViewModel = function(data) {
    BaseViewModel.call(this);
};
//you only need to do this if you are adding prototype properties
ViewModel.prototype = new BaseViewModel();

To your last point, about overriding load , its no different that putting a load function on your viewmodel normally. 至于你的最后一点,关于覆盖load ,正常情况下将load函数放在viewmodel上没有什么不同。 Javascript allows you to override any objects properties with anything, there are no special steps here. Javascript允许您使用任何内容覆盖任何对象属性,此处没有特殊步骤。

Here is a fiddle demonstrating the inheritance. 这是一个展示遗产的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM