在Knockout视图模型定义之外设置属性值 [英] Set property value outside Knockout view model definition
本文介绍了在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");
};
现在我需要在点击链接时更改视图模型的值,如下所示: / p>
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控制台会显示以下内容消息:
未捕获TypeError:对象函数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屋!
查看全文