gpt4 book ai didi

knockout.js - 如何使用映射插件进行 knockout ?

转载 作者:行者123 更新时间:2023-12-02 21:52:17 26 4
gpt4 key购买 nike

我编写了以下代码

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

JSON 数据如下所示:

{"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"}

我应该如何编写html部分?

我对 JavaScript 很陌生。请帮忙。

最佳答案

您的问题有点误导,因为您似乎正确使用了映射插件。

不正确的是您使用 knockout 的方式。您每 3 秒轮询一次,加载数据然后重新绑定(bind)。建议您对于典型的 KO 应用程序仅调用 applyBindings 一次。

如果您定期更新模型,您使用映射插件的方法是正确的。我就是这样做的。

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

还有一个 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>

希望这有帮助。

关于knockout.js - 如何使用映射插件进行 knockout ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com