简体   繁体   中英

Can't get Knockout.js to update an observable object property

I have an object with a public property:

function MyClass() {
    var self = this;
    self.test = 'foo';
    self.changeTest = function() {self.test = 'bar';}
}

var myobj = new MyClass();

The property can be accessed by some of the objects methods and from the "outside". Now, if I create and bind a View Model like this:

function AppVMClass() {
    var self = this;
    self.obs_obj = ko.observable(myobj);
}
var vmodel = new AppVMClass();
ko.applyBindings(vmodel);

then invoking myobj.changeTest() wont change the value of observable. Ie if I have something like that in HTML page: < div data-binding="text: obs_obj().test"></div> it would display "foo" even after myobj.changeTest() has been invoked instead of updating.

What am I doing wrong?

ko.observable has no way of knowing when you've modified myobj - you have to "tell" it. Normally, this is done by using the observable directly when you modify a property. This really only makes sense for values (like self.test ), but you're attempting to have an entire object be the observable.

Instead, break out the values that you care about into their own observables, either on the ViewModel or on a separate object if you really care about the separation:

function MyClass() {
    var self = this;
    // Notice that we're creating an observable directly,
    // and setting its value in the changeTest method.
    self.test = ko.observable('foo');
    self.changeTest = function() {self.test('bar');}
}

var myobj = new MyClass();

function AppVMClass() {
    var self = this;
    self.obs_obj = myobj;
}

And change your template (note, don't do obs_obj.test() , as that will just return the value - you want to bind to the observable itself ):

<div data-bind="text: obs_obj.test"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM