Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.12 KB

viewModels.md

File metadata and controls

51 lines (39 loc) · 1.12 KB

ViewModels

The ko.ViewModel is a constructor to define ViewModels.

var Person = ko.ViewModel.extend({
    observables: {
        firstName: "",
        lastName: "",
        fullName: function() {
            return this.firstName() + " " + this.lastName());            
        },
        friends: []
    }
});

var me = new Person({
    firstName: "Jonathan",
    lastName: "Creamer"
});

me.firstName(); // "Jonathan"
me.fullName(); // "Jonathan Creamer"

me.friends.push(new Person({
    firstName: "Tyson",
    lastName: "Cadenhead"
}));

Some of the advantages are, you don't have to type ko.observable() all the time, and if you define a function in your observables property, it will create a ko.computed that is automatically scoped correctly so this points to the right place.

Events

Changing properties also trigger's events on the ViewModels.

var me = new Person({
    firstName: "Jonathan",
    lastName: "Creamer"
});

me.on("change:firstName", function(value) {
    // value === "foo"
});

me.firstName("foo");

The viewModel can publish and subscribe to messages.