在 Knockout 视图模型定义之外设置属性值 [英] Set property value outside Knockout view model definition

查看:25
本文介绍了在 Knockout 视图模型定义之外设置属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的 Knockout 视图模型:

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
});

但是,我找不到设置该值的正确方法,Chrome 控制台显示以下消息:未捕获的类型错误:对象函数 viewModel() { ... } 没有方法 'myValue'

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");
});

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

Whenever you read from window.vm you'll be reading from that actual instance of the viewModel object

这篇关于在 Knockout 视图模型定义之外设置属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆