I have a Knockout view model defined like this:
function viewModel () {
var self = this;
self.myName = ko.observable();
self.myValue = ko.observable("10");
};
Now I needed to change a value of the view model when a link was clicked, like this:
$('a.treeitem').live("click", function (e) {
e.preventDefault();
viewModel.myValue("20"); // this line does not work
});
However, I can't find out the correct way of setting the value, Chrome console shows the following message: Uncaught TypeError: Object function viewModel() { ... } has no method 'myValue'
You can save the view model as a variable like this:
window.vm = new viewModel();
ko.applyBindings(vm);
$('a.treeitem').live("click", function (e) {
e.preventDefault();
window.vm.myValue("20");
});
Whenever you read from window.vm
you'll be reading from that actual instance of the viewModel object
Actually, what I want to do can be done inside the view model definition, so I can change my code to this:
function viewModel () {
var self = this;
self.myName = ko.observable();
self.myValue = ko.observable("10");
$('a.treeitem').live("click", function (e) {
e.preventDefault();
self.myValue("20");
});
};
Now everything works fine. Sometimes, the right way really is the easy one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With