gpt4 book ai didi

javascript - 使用 ko.mapping.fromJS 保留原始值

转载 作者:行者123 更新时间:2023-12-02 15:31:14 24 4
gpt4 key购买 nike

我有一个定义为 ko.observableArray([]) 的值,并使用 ko.mapping.fromJS 将来自 ajax 的数据附加到其中。但是,当我再次使用 ko.mapping.fromJS 时,从 ajax 调用获取的新数据将替换 self.SampleArray 而不是附加新数据。我想保留以前的数据。怎么可能做到呢?

function ViewModel() {
var self = this;

self.SampleArray = ko.observableArray([]);

$.ajax({
..
..
success: function() {
ko.mapping.fromJS(data, {}, self.sampleArray());
}
})
}

最佳答案

尝试将其插入 observableArray 而不是替换它

View 模型:

function ViewModel() {
var self = this;
self.sampleArray = ko.observableArray([{
'Hours': 0.5
}])
setTimeout(function () {
alert('Mock of ajax call')
var newData = ko.mapping.fromJS(data1)();
self.sampleArray.push.apply(self.sampleArray,newData)
}, 2000);
}
ko.applyBindings(new ViewModel())

push.apply 相对于传统循环语句的优势:

If your array / collection has multiple items and if you add (array.push(item) one by one then the subscribers will be notified for each and every push / add operation. Then the UI will have that number of refresh. That will hurt the UI page performances.

But if you use array.push.appy , then you can still add multiple items, but subscribers will be notified only once.

That is the difference and the advantage / usage of this array.push.apply function.

示例工作 fiddle here

使用 utils.forEach 的示例工作 fiddle here

关于javascript - 使用 ko.mapping.fromJS 保留原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297136/

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