在Subscribe函数中从observableArray中删除元素而不再次发送信号

Remove element from observableArray within Subscribe function without signalling it again

本文关键字:不再 信号 删除 函数 Subscribe observableArray 元素      更新时间:2023-09-26

我想做的是:

var queueManagerClass = function() {
  this.queue = ko.observableArray();
    this.queue.subscribe( function(theChangedQueue) {
       // Do some nice things..
       // Nice things are over, remove the last item from the queue..
       this.queue.remove(theChangedQueue.pop());
    }.bind(this));
};

除了两个问题:当我调用this.queue.remove(item);我就会陷入一个无限循环…订阅函数会一次又一次地调用self .

我知道有一个选项可以暂时"取消绑定"订阅函数,但我不能冒这样的风险,我错过了在取消绑定和再次绑定的平均时间插入的queueItem。

我希望你能理解我的(不太好的)英语。

谢谢你的时间!

解决这个问题的一种方法是使它可以检测到您正在删除项目,并在发生时特别忽略该事件。这可以通过使用本地存储"isremoting"状态来实现。例如

var isRemoving = false;
this.queue.subscribe( function(theChangedQueue) {
  if (isRemoving) {
    return;
  }
  // Do some nice things..
  // Nice things are over, remove the last item from the queue..
  isRemoving = true;
  this.queue.remove(theChangedQueue.pop());
  isRemoving = false;
}.bind(this));