Knockout ViewModel 基类,Javascript 继承 [英] Knockout ViewModel base class, Javascript inheritance
问题描述
我最近在很多项目中都使用了 Knockout.js,并且我正在编写很多重复的代码.我希望能够定义一个 BaseViewModel
类并让我的页面特定的 ViewModel 从中继承.我对如何做到这一点有点困惑是 Javascript.这是我的基本 BaseViewModel
:
I have been using Knockout.js for a lot of projects lately, and I am writing a lot of repetitive code. I would like to be able to define a BaseViewModel
class and have my page-specific ViewModels inherit from it. I am a bit confused about how to do this is Javascript. Here is my basic 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));
我希望能够在 BaseViewModel
中列出诸如 load
之类的方法的签名,然后在继承的 ViewModel 中给它们定义.这有可能吗?我在网上找到了一些解决方案,但它们都依赖于定义函数/类来使继承工作.
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. 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.
推荐答案
由于您的 BaseViewModel
只是将所有属性/方法添加到 this
(而不是使用原型) 那么这很容易:
Since your BaseViewModel
is just adding all of the properties/methods to this
(and not using prototype) then it is pretty easy:
在您的新视图模型中,只需调用 BaseViewModel
:
In your new view models, just call 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();
这篇关于Knockout ViewModel 基类,Javascript 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!