问题
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