Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS Model Inheritance

Tags:

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.

example

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; }; 

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

like image 682
BillPull Avatar asked Feb 19 '13 19:02

BillPull


1 Answers

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

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

inside the StandardItemModel

like this: http://jsfiddle.net/marceloandrader/bhEQ6/

like image 97
Marcelo A Avatar answered Sep 25 '22 17:09

Marcelo A