简体   繁体   English

无法获取Knockout.js来更新可观察对象属性

[英]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. 然后调用myobj.changeTest()不会改变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. 即如果我在HTML页面中有类似的东西: < div data-binding="text: obs_obj().test"></div>即使调用了myobj.changeTest()而不是更新,它也会显示“foo” 。

What am I doing wrong? 我究竟做错了什么?

ko.observable has no way of knowing when you've modified myobj - you have to "tell" it. ko.observable无法知道你何时修改了myobj - 你必须“告诉”它。 Normally, this is done by using the observable directly when you modify a property. 通常,这是通过在修改属性时直接使用observable来完成的。 This really only makes sense for values (like self.test ), but you're attempting to have an entire object be the observable. 这实际上只对值(如self.test )有意义,但是你试图将整个对象作为可观察对象。

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: 相反,如果你真的关心分离,可以在ViewModel上或在单独的对象上将你关心的值分解为他们自己的observable:

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 ): 并更改你的模板(注意,不要做obs_obj.test() ,因为它只会返回值 - 你想绑定到observable本身 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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