gpt4 book ai didi

javascript - ko 可观察数组在删除最后一个元素时不触发

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

我有一张 map ,其中有一个元素显示当前正在加载哪些图层。我在一个可移除的可观察数组中保存了一个层名称列表。加载新图层时,它们会按预期显示。当层完成加载时,它们将按预期移除,除了最后一个。即使调试显示它绑定(bind)到的列表现在是空的,它也不会被删除。

初始化可观察对象:

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

即将加载图层时:

self.layerLoadingStarted(layerName);

层加载时触发的事件:

layer.events.register('loadend', layer, function () {
self.layerLoadingFinished(layerName);
});

以及被调用的函数:

self.layerLoadingStarted = function (layerName) {
self.currentlyLoadingLayers.push(layerName);
};

self.layerLoadingFinished = function(layerName) {
for (var i = self.currentlyLoadingLayers().length - 1; i >= 0; i--) {
if (self.currentlyLoadingLayers()[i] === layerName) {
self.currentlyLoadingLayers().splice(i, 1);
}
}
//if (self.currentlyLoadingLayers().length === 0) self.currentlyLoadingLayers([]);
};

如果我取消注释上面函数中的最后一行,那么一切正常。为什么这是必需的?数组现在为空的事实不应该被自动观察到吗?

我的绑定(bind):

<div id="layersLoadingMessage" data-bind="visible: $root.currentlyLoadingLayers() && $root.currentlyLoadingLayers().length">
<div data-bind="foreach: $root.currentlyLoadingLayers">
<div data-bind="text: $data"></div>
</div>
</div>

最佳答案

observableArray 中的项目被添加或删除,或者整个集合被替换时,Knockout 将通知订阅者。但只有通过 observableArray 对象而不是直接操作底层数组来完成。

所以这将通知订阅者:

self.currentlyLoadingLayers.splice(i, 1)

这不会:

self.currentlyLoadingLayers().splice(i, 1)

这将:

self.currentlyLoadingLayers([])

请检查 observableArray 的文档.

我在你的代码中添加了一些注释和一些解释:

self.layerLoadingFinished = function(layerName) {
for (var i = self.currentlyLoadingLayers().length - 1; i >= 0; i--) {
if (self.currentlyLoadingLayers()[i] === layerName) {
//this line modifies the underlying array directly bypassing ko's notifiers
//change this to self.currentlyLoadingLayers.splice(i, 1)
//to notify subscribers after each item is removed
self.currentlyLoadingLayers().splice(i, 1);
}
}
//this line uses self.currentlyLoadingLayers([]) which changes
//the underlying array through ko and will notify subscribers
if (self.currentlyLoadingLayers().length === 0) self.currentlyLoadingLayers([]);
};

关于javascript - ko 可观察数组在删除最后一个元素时不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703314/

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