yopanw
Last Updated: February 25, 2016
·
3.554K
· surfpartyusa

Typescript Knockout.js Base View Model

Now that i've started using Typescript along with Knockout.js i've found that having a base model that all my view models inherit from is fucking useful as hell. the methods and properties this view model contain cover basic CRUD operations that are common in knockout apps. A typical view model contains a collection of models that you need to select, remove, deselect, etc. The costructor accepts a string "Model" that will be the name of the model class it is to represent.

class BaseViewModel {

//properties
Model: string;
Selected: KnockoutObservableAny;
Collection: KnockoutObservableArray;

//methods
public New: () => void;
public Select: (model: any) => void;
public Deselect: () => void;
public Add: (model: any) => void;
public Remove: (model: any) => void;
public Clean: () => void;


constructor(model: string) {

    //property definitions
    this.Model = model;
    this.Selected = ko.observable();
    this.Collection = ko.observableArray();



    //method definitions

    this.Select = (model) => {
        this.Selected(model);
    }
    this.Deselect = () => {
        this.Selected(null);
    }
    this.Add = (model) => {
        this.Collection.push(model);
    }
    this.Remove = (model) => {
        this.Collection.remove(model);
    }

    this.New = () => {
        var model = new window[this.Model]; this.Add(model);
    }


    this.Clean = () => {
        this.Collection([]);
        this.Selected(null);
    };
}

}