Knockout JS 模型继承 [英] Knockout JS Model Inheritance

查看:24
本文介绍了Knockout JS 模型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有三个相对相似的淘汰赛模型,我想扩展一个基本模型以组合通用属性,而不是重复三遍.

I have three relatively similar knockout models in my application and I would like to extend a base model to combine common properties rather than repeat myself three times.

例子

var ItemModel = function (item) {
  var self = this;

  self.order = ko.observable(item.order);
  self.title = ko.observable(item.title);
  self.price = ko.observable(item.price);
  self.type = ko.observable(item.type);
};

var StandardItemModel = function (item, cartItemTypes) {
  var self = this;

  self.order = ko.observable(item.order);
  self.title = ko.observable(item.title);
  self.price = ko.observable(item.price);
  self.type = ko.observable(item.type);

  self.isInCart = ko.computed(function () {
    return cartItemTypes().indexOf(item.type) > -1;
  }, self);

  self.itemClass = ko.computed(function () {
     return self.isInCart() ? "icon-check" : "icon-check-empty";
  }, self);
};

var CustomItemModel = function (item) {
  var self = this;

  self.order = ko.observable(item.order);
  self.title = ko.observable(item.title);
  self.price = ko.observable(item.price);
  self.type = ko.observable(item.type);

  self.icon = item.icon;
};

我想使用 ItemModel 作为基类,并根据需要添加额外的属性.

I would like to use ItemModel as a base class and just add the extra properties as necessary.

推荐答案

我觉得你可以像这样使用 ko.utils.extend

I think you can use ko.utils.extend like this

ko.utils.extend(self, new ItemModel(item));

在 StandardItemModel 内部

inside the StandardItemModel

像这样:http://jsfiddle.net/marceloandrader/bhEQ6/

这篇关于Knockout JS 模型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆