Reputation: 227
I would like to implement knockout functionality to an already existing page. Therefore I want to manipulate with the ViewModel data from existing script. I have mocked up an example but it doesn't work correctly.
A ViewModel is correctly bound to the UI (try typing in the input). It functions also when I modify the ViewModel data in backend (by pressing a button). However when I modify the input value again by typing into the input box, the data is not changed.
How can I propperly modify ViewModel data from backend (some existing code manipulates the data). Please note, that I have used jQuery click event as an example. Existing code may manipulate the data in the different manner.
Here is the code (HTML):
<!-- View -->
<p>First name: <strong data-bind="text: myName"></strong></p>
<input data-bind="value: myName"></input>
<button>Click me</button>
And JS:
// ViewModel
var AppViewModel = function() {
this.myName= ko.observable("John Doe");
}
// ViewModel instance
var app = new AppViewModel();
// Activates knockout.js
ko.applyBindings(app);
// Custom external code that changes the data in the ViewModel instance
$("button").click(function() {
app.myName= ko.observable("Steve Peterson");
ko.applyBindings(app);
});
Upvotes: 2
Views: 5573
Reputation: 3700
Instead of creating new observable in click handler
app.myName= ko.observable("Steve Peterson");
modify value of existing observable
app.myName("Steve Peterson");
Working example http://jsfiddle.net/S9HBq/
Upvotes: 4