javascript 视图模型之外的 Knockout.js 调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9960881/
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 08:21:56  来源:igfitidea点击:

Knockout.js calling method outside of view model

javascriptdata-bindingknockout.jshighcharts

提问by Phil Ninan

I want to make my data accessible outside of my view model. So I created a view model object but I'm having trouble binding its properties. Note that everything is working properly inside my view model.

我想让我的数据在我的视图模型之外访问。所以我创建了一个视图模型对象,但我在绑定它的属性时遇到了麻烦。请注意,在我的视图模型中一切正常。

Basically a simplified pseudo-code:

基本上是一个简化的伪代码:

function Users() {
    name;
    date;
}

function userHealthModel() {
     function createUsers() { new Users[] };
}

self.userModel = ko.observable(new userHealthModel());
self.userModel.createUsers();

If I call the createUsersmethod inside my model my bind works fine.

如果我createUsers在模型中调用该方法,则绑定工作正常。

Here is a jsFiddle, note my problem is all the way at the end of the JS, I commented it: http://jsfiddle.net/fourgates/jpk22/1/

这是一个jsFiddle,注意我的问题一直在JS的末尾,我评论了它:http: //jsfiddle.net/fourgates/jpk22/1/

I'm new to JS and KO. not really sure how to use $root, $parent, etc. Please help a fellow programming enthusiast! Many thanks in advance!

我是 JS 和 KO 的新手。不太确定如何使用 $root、$parent 等。请帮助编程爱好者!提前谢谢了!

回答by Niko

I'm still not 100% sure if I understand what you're trying to do, but here are some thoughts about the code in your fiddle:

我仍然不能 100% 确定我是否理解你想要做什么,但这里有一些关于你小提琴中的代码的想法:

If you have something like

如果你有类似的东西

var self = this;

in the global scope (= not in a function), thispoints to the window object. Therefore this does not make any sense.

在全局范围内(= 不在函数中),this指向 window 对象。因此,这没有任何意义。

self.userModel = ko.observable(new userHealthModel());

Creating an observable of a view model is not necessary - you don't expect the whole model to change, right? It will always stay a user model and not suddenly become a "message model" or whatever.

创建视图模型的 observable 不是必需的 - 您不希望整个模型发生变化,对吗?它将始终保持用户模型,而不会突然变成“消息模型”或其他什么。

If you want to call a method of your view model from the outside, just make an instance:

如果要从外部调用视图模型的方法,只需创建一个实例:

var userModel = new userHealthModel();
userModel.createUsers();

// Use "userModel" to access the methods and properties
// like you're using "self" inside the view model:
userModel.users2()[1].userId(5);

// now apply the binding to THE SAME view model
ko.applyBindings(userModel);

http://jsfiddle.net/jpk22/3/

http://jsfiddle.net/jpk22/3/

If this isn't what you were looking for, let me know!

如果这不是您要找的,请告诉我!