KnockoutJS computed observable within an observable

被刻印的时光 ゝ 提交于 2020-01-05 05:03:35

问题


I have a ViewModel containing the following observable:

self.obFoo = ko.observable({
    foo: ko.observable(""),
    bar: ko.observable("")
});

Now I want to add a new computed observable to obFoo that depends on both foo and bar, something like this:

self.obFoo = ko.observable({
    foo: ko.observable(""),
    bar: ko.observable(""),
    foobar: ko.computed(function(){
          return foo() + bar();
    })
});

The problem is that foo and bar are not defined within the scope of foobar. I tried adding 'this' or even 'self.obFoo' as a second parameter to the computed but neither worked.

Is there a way to get the right scope into the computed foobar?


回答1:


The easiest solution is to create a proper constructor function for your object:

var MyObject = function(){
    this.foo = ko.observable("foo");
    this.bar = ko.observable("barr");
    this.foobar = ko.computed(function(){
          return this.foo() + this.bar();
    }, this);
}

And use the constructor function to create your object instead of the object literal:

var ViewModel = function () {
    var self = this;
    self.obFoo = ko.observable(new MyObject());
}

Demo JSFiddle.




回答2:


Or you could do this:

var o={
    foo: ko.observable(""),
    bar: ko.observable("")

};
o.foobar= ko.computed(function(){
          return o.foo() + o.bar();
    });

self.obFoo = ko.observable(o);


self.obFoo().foobar();


来源:https://stackoverflow.com/questions/21256964/knockoutjs-computed-observable-within-an-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!