Search code examples
javascriptknockout.jsradix

Using Base2 with KnockoutJS View Models


I am using Base2 as a means to allow us to easily do inheritance in our system, aswell as using KnockoutJS for some UI interactions.

We have defined a base class for our ViewModels

BaseViewModel = Base.extend({
    ...
});

Which we then extend for our view models:

ExampleViewModel = BaseViewModel.extend({
    text: ko.observable("")
});

However there seems to be a problem. When you create 2+ instances of the view model (say if you are pushing them in to an observableArray and using templates to build up a UI) it seems like any changes made to a bound field, updates all view models rather than just the one it's bound to.

Does anybody know why this might be?


Solution

  • Because the extension is not actually instantiating a new observable, its just copying the reference.

    I think you can do something like this:

    ExampleViewModel = BaseViewModel.extend({
        constructor: function() {
            this.text = ko.observable("");
        }
    });
    

    Not as nice though as normal Base2 syntax, but just a limitation in how Knockout is implemented due to issues with properties.