Javascript inheritance in Knockout ViewModels

Knockout is an elegant way of updating the user interface using Javascript View models. Javascript has an inheritance model which allows for a View model hierarchy. As an illustration, consider the following HTML:

The name and detail properties of the View model are bound to the respective div elements. The Javascript which applies the binding is shown below:

Simple inheritance

Klaus Komenda has another article that explains Javascript inheritance. Creating Knockout View model hierarchy requires more understanding of Javascript inheritance. To illustrate inheritance, the Model class in the above example is derived from the BaseModel class.

When a new Model object is created, the BaseModel constructor is invoked. The Model object will have both the name and detail properties.

Overriding functions

It is possible to override base class functions. For example, both BaseModel and Model classes can define a load function. From the load function of the Model class, it is possible to invoke the load function of the BaseModel class. By using prototypes to define functions, the base class functions can be invoked from the derived class.

The following Javascript code explains how to do function overridding in Javascript:

There is a good Stackoverflow article which explains the benefits of declaring a function via prototypes.

Inheriting observable properties

Any observable property defined in a Knockout View model is a function. When using prototypes to define base classes, all the objects created using the sub class, will share the same base class function. So, any observable property defined in the base class is shared among multiple object instances.

In the above example, if we create a collection of Model objects, with the following properties: (“a1”, “a1 detail”), (“a2”, “a2 detail”), the Model objects will have the same name property value of “a2”. This is because of prototype inheritance: name property is defined in the base class prototype and is shared among all object instances. To overcome the problem, any View model which is part of a collection should use constructor inheritance as follows:

The object is created using the base class constructor. Extension functions are appended to the object. Finally, the object with inherited and extended functions is returned from the constructor call.

Leave a Reply

Your email address will not be published. Required fields are marked *