javascript 在 Knockout 视图模型定义之外设置属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9474185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:47:45  来源:igfitidea点击:

Set property value outside Knockout view model definition

javascriptknockout.js

提问by Nelson Reis

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'

但是,我找不到设置值的正确方法,Chrome 控制台显示以下消息: Uncaught TypeError: Object function viewModel() { ... } has no method 'myValue'

回答by soniiic

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.vmyou'll be reading from that actual instance of the viewModel object

每当您读取时,window.vm您都会读取 viewModel 对象的实际实例

回答by Nelson Reis

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 reallyis the easy one.

现在一切正常。有时,正确的方法确实是简单的方法。