Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property value outside Knockout view model definition

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'

like image 918
Nelson Reis Avatar asked Feb 27 '12 23:02

Nelson Reis


2 Answers

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

like image 82
soniiic Avatar answered Sep 20 '22 16:09

soniiic


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.

like image 43
Nelson Reis Avatar answered Sep 20 '22 16:09

Nelson Reis