javascript - 在 Subscribe 函数中从 observableArray 中删除元素,而无需再次发出信号

标签 javascript knockout.js

我想做的是:

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..

我知道有一个选项可以暂时“取消绑定(bind)”订阅功能,但我不能冒险错过在取消绑定(bind)和再次绑定(bind)的同时插入的queueItem。

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

感谢您的宝贵时间!

最佳答案

解决此问题的一种方法是让它可检测到您正在删除该项目,并在发生这种情况时专门忽略该事件。这可以通过使用本地存储“isRemoving”状态来完成。例如

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));

关于javascript - 在 Subscribe 函数中从 observableArray 中删除元素,而无需再次发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650430/

相关文章:

javascript - 将 javascript 间接插入 html 页面的方法

javascript - 如何检查浏览器中是否存在同名的cookie,并据此对特定页面进行授权

javascript - 遍历 DOM 从点击的元素获取节点

javascript - 如何用纯javascript控制奇观呈现?

asp.net-mvc - 使用 Knockout JS + MVC + 服务器端模型验证显示错误?

javascript - 使用Javascript从div中的HTML生成pdf

knockout.js - ko.toJSON 似乎忽略了字段

javascript - Knockout 没有使用我的数据渲染模板

javascript - 将挖空 View 模型绑定(bind)到 Bootstrap Tree View

Knockout.js url 路由