问题描述
我想了解Knockout JS.令我困扰的是我绑定的数据被清空了.这很烦人,因为我想显示从服务器检索到的数据.
I'm trying to understand Knockout JS. What bothers me is that the data I bind gets blanked out. It's annoying because I want to show the data I retrieve from the server.
一个例子:
Name: <span class="name"><?php echo $data->name; ?></span>
结果是:Name: John B
现在,如果我将此数据与Knockout绑定到此:
Now if I data-bind this with Knockout to this:
Name: <span data-bind="text: name" class="name"><?php echo $data->name; ?></span>
结果是:Name:
JS类似于:
var viewModel = {
name: ko.observable() // Initially blank <--- this is the culprit
};
ko.applyBindings(viewModel);
那我需要怎么做才能显示/保存数据?
淘汰赛无法像Angular JS一样保留数据吗?
So what do I need to do in order to show / keep the data?
Can't Knockout somehow keep the data like Angular JS does?
注意我正在使用Yii MVC框架来处理许多服务器端内容.使用它在页面加载时加载数据,使我免于编写大量JS Ajax代码.我想使用Knockout减少我拥有的jQuery代码的数量,而不是添加它:)
NoteI'm using Yii MVC framework to handle a lot of server side stuff. Using that to load data on page load, saves me from writing a lot of JS Ajax code. I wanted to use Knockout to reduce the amount of jQuery code I have, not add to it :)
推荐答案
这里有两种解决方法,您可以尝试避免两次声明数据(请注意,它们没有直接提供将数据保存在html文件中的方法):
Here are two workaround you can try to avoid declaring your data twice (note that they do not directly provide a way to keep your data in your html file) :
使用以下方法创建一个php文件:
Create a php file with:
var defaultVm = {
name: '<?php echo $data->name; ?>',
anyVariable: '<?php echo $data->anyVariable; ?>'
}
然后,您将此php文件作为js文件包含在内,并使用它初始化视图模型:
Then you include this php file as a js file and init your viewmodel with it:
var viewModel = {
name: ko.observable(defaultVm.name);
anyVariable: ko.observable(defaultVm.anyVariable);
};
ko.applyBindings(viewModel);
解决方案2:使用 ko.mapping 插件
使用以下方法创建一个php文件:
Solution 2: Use the ko.mapping plugin
Create a php file with:
{
"name": "<?php echo $data->name; ?>",
"anyVariable": "<?php echo $data->anyVariable; ?>"
}
然后在您的js中,您可以使用ko.mapping插件:
Then in your js, you can use the ko.mapping plugin:
var viewModel = function (data) {
ko.mapping.fromJS(data, {}, this);
};
ko.applyBindings(new viewModel(getYourPhpFileTheWayYoulike));
这使您可以通过以下方式异步获取数据(如果需要):
This allows you to get your data asynchronously (if you want) with something like:
$.getJSON("yourphpmodelurl", function (data) {
ViewModelInstance = new viewModel(data);
ko.applyBindings(ViewModelInstance);
}
这篇关于如何保持从服务器加载的数据不被“清空"?由Knockout JS加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!