Ran*_*dra 4 knockout-mapping-plugin knockout.js
我写了以下代码
$(function() {
function get_updates () {
$.getJSON('/new-lines.json', function(data) {
var fullViewModel= ko.mapping.fromJS(data);
ko.applyBindings(fullViewModel)
});
}
function poll()
{
setTimeout(function(){
get_updates();
poll();},3000)
}
poll()
});
Run Code Online (Sandbox Code Playgroud)
JSON数据如下所示:
{"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"}
Run Code Online (Sandbox Code Playgroud)
我应该怎么写这个html部分?
我是javascript的新手.请帮忙.
mad*_*kay 10
您的问题有点误导,因为您似乎正确使用了映射插件.
什么是不正确的是你使用淘汰赛的方式.您每3秒轮询一次,加载数据然后重新绑定.建议您只applyBindings为典型的KO应用程序调用一次.
如果您定期更新模型,则使用映射插件的方法是正确的.这是我怎么做的.
http://jsfiddle.net/madcapnmckay/NCn8c/
$(function() {
var fakeGetJSON = function () {
return {"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"};
};
var viewModel = function (config) {
var self = this;
// initial call to mapping to create the object properties
ko.mapping.fromJS(config, {}, self);
this.get_updates = function () {
ko.mapping.fromJS(fakeGetJSON(), {}, self);
};
};
// create viewmodel with default structure so the properties are created by
// the mapping plugin
var vm = new viewModel({ state: "M", qualities: [], name: "Foo" });
function poll()
{
setTimeout(function(){
vm.get_updates();
poll();
}, 3000)
}
// only one call to applybindings
ko.applyBindings(vm);
poll();
});
Run Code Online (Sandbox Code Playgroud)
和一个示例HTML
<h1>Name <span data-bind="text: name"></span></h1>
<h2>State <span data-bind="text: state"></span></h2>
<ul data-bind="foreach: qualities">
<li data-bind="text: $data"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.