Reputation: 13
I'm using knockout.js 3.0 and I'm stuck with some simple conclusion:
var self = this;
self.selectedItem = ko.observable("default text");
ko.computed(function () {
if (this.selectedItem() != "default text") {
this.selectedItem("success");
}
}, self);
But when I change my observable, computed callback function is triggering again. So how to prevert it?
Upvotes: 1
Views: 838
Reputation: 473
You could use a writable computed observable like this:
var self = this;
self.selectedItem = ko.observable("default text");
self.notifySelectedItem = ko.computed({
read: self.selectedItem,
write: function (value) {
if (this.selectedItem() != "default text") {
self.selectedItem(value);
alert("success");
}
}
});
Use notifySelectedItem instead of selectedItem wherever you need to be notified about the change. It will display the selectedItem value, and call the write callback on update. You might need to move the self.selectedItem(value) outside the if block, according to your needs.
Upvotes: 1
Reputation: 1043
Typically, you assign a variable name to your computed function so it can be referenced from somewhere in your view. Also computed is not a "callback", that is different thing entirely although a computed could be used as a callback function I suppose. A ko computed observable is usually an observable that you want to have react to other observables changing although there are many other uses for it.
var self = this;
self.selectedItem = ko.observable("default text");
self.testTextChange = ko.computed(function () {
if (self.selectedItem() != "default text") {
alert("success"); // Changed this to alert, otherwise, you will change the value of the input as you stated in your question.
}
});
Then in your view, something like
<input data-bind="text: selectedItem" />
<button data-bind="click: testTextChange">Click Me</button>
This is a completely arbitrary example though, which brings up several questions, what do you have in your view for your data-bind
and what exactly are you trying to do with this?
Upvotes: 1
Reputation: 63729
You seem to be confused about how computed observables are used, since you're not saving the observable on a property of self
at all.
In any case, you do two things that will cause problems for you when combined:
selectedItem
selectedItem
This will (or at least: might) cause an endless loop, because the computed will be recalculated every time the underlying observable changes, but it's changing that observable itself.
Even though you can, it's probably not wise to update (observable) variables in a computed observable at all, at least not in the read
(a.k.a. "getter") version.
PS. You may be looking for writable computed observables.
Upvotes: -1