Reputation: 3
I'm unable to create two-way binding with knockout observable. The data is getting initialized properly, but updating the value(x in UI) during a click function is where I'm finding difficulties. Any help would be greatfull, as I'm new to knockout making transition from angular for a client,
Demo:https://jsfiddle.net/govardhan_s92/abq9j5t4/1/
Thanks in advance.
Html:
<div class='liveExample'>
<p data-bind="text:x,click:test()"></p>
</div>
Javascript:
var ViewModel = function() {
this.x=ko.observable("");
this.x = "something 1";
this.test = function() {
this.x = "something 2"
}
};
ko.applyBindings(new ViewModel());
Upvotes: 0
Views: 52
Reputation: 56720
First you assign this.x
to become a ko.observable
(which makes it a function reference to the ko.observable function):
this.x = ko.observable("");
In the next line you tell this.x
to instead become a regular string variable, which overwrites the ko.observable
function reference:
this.x = "something1";
If you want to update an observable variable's value (remember: it's a function!), you need to pass it to the variable as a function argument rather than assigning the new value to the variable (which overwrites the observable):
this.x("something1");
Also, your click binding should be click: test
not click: test()
since otherwise you assign to the click handler whatever executing text()
returns.
<p data-bind="text: x, click: test"></p>
Upvotes: 3
Reputation: 402
when you assign ko.observable() to x, this.x becomes a function which accepts the new value to be updated
You need to do this
var ViewModel = function() {
this.x=ko.observable("");
this.x("something 1");
this.test = function() {
this.x("something 2")
}
};
ko.applyBindings(new ViewModel());
Upvotes: 1