这是一个有趣的问题,想知道是否有人有同样的想法或已经实现了它。
我的场景:
我有一个可观察的数组,在第一次加载时,我想创建一堆<div>
标签。很简单,Knockout 为我做了这件事。但是,单击按钮后,我想将另一组结果加载到相同 <div>
的元素中,而不是重新渲染它们(从外观上看,Knockout 默认行为)。
如:
function viewModel() {
var self = this;
self.testArray = ko.observableArray([]);
self.loadMore = function () {
var length = self.testArray().length;
if (length > 0) {
console.log('loading into divs');
// Load into original <div>'s
// This is deleting the old <div>'s from the DOM and creating new ones...
// How can I just replace the original <div> content for performance gains?
for (var i = 0; i < 10; i++) {
self.testArray.replace(self.testArray()[i], new { text: 'New Text' });
}
}
else {
// Create the <div>'s by pushing items to the array
for (var i = 0; i < 10; i++) {
self.testArray.push(ko.observable(new { text: 'New Text' }));
}
}
};
}
var model = new viewModel();
model.loadMore();
ko.applyBindings(model);
<!-- ko foreach: testArray -->
<div data-bind="text: text"></div>
<!-- /ko -->
<button data-bind="click: loadMore">Next</button>
比较容易理解...
** 首次加载 **
<div></div> - created
<div></div> - created
<div></div> - created
<div></div> - created
<div></div> - created
** 第二次加载 **
<div></div> - deleted
<div></div> - deleted
<div></div> - deleted
<div></div> - deleted
<div></div> - deleted
<div></div> - created
<div></div> - created
<div></div> - created
<div></div> - created
<div></div> - created
我在第二次加载时想要什么...
<div></div> - edited
<div></div> - edited
<div></div> - edited
<div></div> - edited
<div></div> - edited
有任何想法吗?我试图这样做是为了提高性能,而不是<div>
在 DOM 中重新创建 ',我只想重新使用那里的那些。