In the code below, I would expect the span text to say ‘test clicked’ after clicking the test button. I can see the selectedItem.title being updated. Why doesn’t this data-bind work?
http://jsfiddle.net/TheMetalDog/C7k6d/
<button data-bind="click: setItem">Test</button>
Item <span data-bind="text: $root.selectedItem.title"></span>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
—
var viewModel = {};
viewModel.selectedItem = ko.observable();
viewModel.setItem = function() {
viewModel.selectedItem({title: 'clicked'});
};
ko.applyBindings(viewModel);
You have two errors here:
1 . You’re applying binding to a model and uses the
titleproperty, which does not exist until you click on the button. If you’re using model’s property, you need to define it before binding:2 . When you’re using observables you need to put
()after them, as far as it’s not just a variable but a function. So you need:And you can play with it here http://jsfiddle.net/fMKPs/