Set property value outside Knockout view model definition

后端 未结 2 1800
执笔经年
执笔经年 2021-01-04 06:03

I have a Knockout view model defined like this:

function viewModel () {
    var self = this;

    self.myName = ko.observable();
    self.myValue = ko.observ         


        
相关标签:
2条回答
  • 2021-01-04 06:25

    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

    0 讨论(0)
  • 2021-01-04 06:32

    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.

    0 讨论(0)
提交回复
热议问题