gpt4 book ai didi

javascript - Knockout.js 映射插件如何更新数据

转载 作者:行者123 更新时间:2023-11-30 17:11:31 24 4
gpt4 key购买 nike

以下代码将获取 JSON 数据并将其正确绑定(bind)到 View ,但是当我获取更新的数据时, View 不会更新。数据已更改但 View 未更新。任何想法我做错了什么?我无法理解映射插件的工作原理。

jQuery(document).ready(function() {

setInterval(LeaderboardViewModel, (10 * 500));

function LeaderboardViewModel() {
var self = this;

this.ArrayOfPlayers = ko.mapping.fromJS([]);

$.ajax({
type: 'GET',
url: 'http://localhost:5500/leaderboard/',
context: this,
success: function(data) {
self.SuccessfullyRetrievedModelsFromAjax(data);
},
dataType: 'json'
});

this.SuccessfullyRetrievedModelsFromAjax = function(data) {
var array = $.map(data.leaderboard, function(value, index) {
return [value];
});

console.log(array);
ko.mapping.fromJS(array, {}, self.ArrayOfPlayers);
};
}

ko.applyBindings(new LeaderboardViewModel());

});

以下 HTML 在我加载页面时正确呈现数据:

<tbody data-bind="foreach: ArrayOfPlayers">

编辑:当我加载页面时它工作正常。设置间隔部分不起作用。

获取数据:

{
"leaderboard": {
"1": {
"deaths": 52,
"game_count": 13,
"game_defeats": 0,
"game_deserts": 0,
"game_draws": 0,
"game_wins": 13,
"id": 2,
"kills": 78,
"level": 8,
"rank": 1,
"xp": 3260
},
"10": {
"deaths": 78,
"game_count": 13,
"game_defeats": 13,
"game_deserts": 0,
"game_draws": 0,
"game_wins": 0,
"id": 1,
"kills": 52,
"level": 5,
"rank": 10,
"xp": 1570
},
}

编辑 2:没有控制台错误。

最佳答案

那是因为你在 applyBinding 中使用了关键字 'new',但是在函数定义中设置了超时。它必须以这种方式工作:

jQuery(document).ready(function() {

function LeaderboardViewModel() {
var self = this;
this.ArrayOfPlayers = ko.mapping.fromJS([]);

this.SuccessfullyRetrievedModelsFromAjax = function(data) {
var array = $.map(data.leaderboard, function(value, index) {
return [value];
});

console.log(array);
ko.mapping.fromJS(array, {}, self.ArrayOfPlayers);
};

self.UpdateMappings = function(){
$.ajax({
type: 'GET',
url: 'http://localhost:5500/leaderboard/',
context: this,
success: function(data) {
self.SuccessfullyRetrievedModelsFromAjax(data);
},
dataType: 'json'
});
};
}

var viewModel = new LeaderboardViewModel();
setInterval(viewModel.UpdateMappings, (10 * 500));

ko.applyBindings(viewModel);

});

关于javascript - Knockout.js 映射插件如何更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26909074/

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