Gridster 在 beforeRemove Knockout 回调中阻塞 li 节点

Gridster blocks li node in beforeRemove Knockout callback

使用 KnockoutJS 3.3.0 和原始 Ducksboard gridster 存储库的 0.5.6 版本。我有一个绑定到我的 gridster ul 的 observableArray。我在模板绑定中使用 afterAdd 和 beforeRemove 回调来跟踪 knockout 何时为我的列表中的项目添加和删除 DOM 节点,以便我可以通知 Gridster。

有趣的是,li 节点永远不会返回到 beforeRemove 回调,以便我适当地处理它们。例如,当删除数组中的项目时,与该项目关联的文本节点会触发 beforeRemove 回调,但不会触发 li 本身。有一些方法可以解决它,但这表明 gridster/jquery 和 knockout 跟踪 DOM 的方式之间存在一些不兼容,并且可能至少是我正在跟踪的内存问题的一部分。

在 fiddle 的控制台输出中,您可以看到 li 节点已正确添加,但是当对象从 knockout 数组中移除时,绑定到 beforeRemove 回调的 removeGridster 函数永远不会触发li 节点。我已经研究了几个小时的源代码,但没有发现任何会导致这种情况的原因。

有 knockout/jquery/gridster 专家愿意插话吗?

http://jsfiddle.net/8u0748sb/8/

HTML

<button data-bind='click: add1'> Add 1 </button>
<button data-bind='click: add20'> Add 20 </button>
</button>

<div class="gridster">
<!-- The list.  Bound to the data model list. -->
  <ul data-bind="template: {foreach: board().widgets, afterAdd: board().addGridster, beforeRemove: board().removeGridster}"
      id="board-gridster">
    <li data-bind="attr: {'id': id, 'data-row': dataRow, 'data-col': dataCol,'data-sizex': datasizex, 'data-sizey': datasizey}"
        class='gs-w'
        style='list-style-type: none; background:#99FF99;'>
      <div data-bind="click: removeSelected"
           style='float:right; cursor: pointer'>
        X
      </div>

      <div data-bind='if: state() === "Minimized"'>
        <span data-bind="style:{ 'backgroundColor': color">
          -
        </span>
      </div>

      <div data-bind='if: state() === "Maximized"'>
        <span data-bind="text: value">
        </span>
      </div>
    </li>
  </ul>
</div>

JS

var vm;

$(function() {
  vm = new MainViewModel();
  ko.applyBindings(vm);
});

function MainViewModel() {
  var self = this;

  self.board = ko.observable(new BoardViewModel());

  self.add1= function() {
    self.board().addRandomWidget();
  };

  self.add20 = function() {
    for(var i = 0; i < 20; i++) {
      self.add1();
    }
  };
};

function BoardViewModel () {
  var self = this;

  // Used for binding to the ui.
  self.widgets = ko.observableArray([]);

  // Initialize the gridster plugin.
  self.gridster = $(".gridster").gridster({
    widget_margins : [8, 5],
    widget_base_dimensions : [100, 31],
    extra_rows: 2,
    resize : {
      enabled : false
    }
  }).data('gridster');

  self.cols = self.gridster.cols;
  self.rows = self.gridster.rows;


  /**
   * Used as a callback for knockout's afterAdd function.  This will be called 
   * after a node has been added to the dom from the foreach template.  Here,
   * we need to tell gridster that the node has been added and then set up 
   * the correct gridster parameters on the widget.
   */
  self.addGridster = function (node, index, obj) {
    var widget = $(node);
    var column = widget.attr("data-col");

    console.log('adding: ');
    console.log(node);

    // afterAdd is called one for each html tag.
    // We only want to process it for the main tag, which will have a data-col
    // attribute.
    if (column) {
      // width and height
      var sizeX = obj.datasizex;
      var sizeY = (obj.state() === "Minimized" || obj.state() === "Closed")? 1 : obj.datasizey;

      // add the widget to the next position
      self.gridster.add_widget(widget, sizeX, sizeY);
    }
  };

  /**
   * Used as a callback for knockout's beforeRemove.  Needs
   * to remove node parameter from the dom, or tell gridster
   * that the node should be removed if it is an li. 
   */
  var hackPrevWidget = null;
  self.removeGridster = function (node, index, widget) {
    // TODO this is never called on the li.  
    console.log("Removing");
    console.log(node);

    // Only including this so that the widget goes
    // away from gridster.  We should not have to 
    // Have this strange hack.  Ideally, we 
    // could check to see if the current node is
    // an li and then remove it from gridster, 
    // but something is preventing it from ever
    // being passed in.  What is happening to this
    // node that causes knockout to lose it?
    if (widget !== hackPrevWidget) {
      self.gridster.remove_widget($('#' + widget.id));
    } else {
      node.parentNode.removeChild(node);
    }
    hackPrevWidget = widget; 
  };


  /**
   * Adds a new widget to the knockout array.
   */
  self.addRandomWidget = function() {
    self.widgets.push(new Widget());
  };

  /**
   * Remove a widget from knockout
   */
  self.removeWidget = function(widget) {
    self.widgets.remove(widget);
  };
};

  var ids = 1;

function Widget(args) {
  var self = this;
  var col, row;

  // We keep an id for use with gridster.  This must be here if we
  // are still using gridster in the widget container.
  self.id = ids++;

  /*------------- Setup size ------------------*/
  self.datasizex = 2;
  self.datasizey = 6;

  /*------------- Setup position ------------------*/
  self.dataRow = 0;
  self.dataCol = 0;

  self.value = ko.observable(Math.random());
  self.state = ko.observable(Math.random() > .5 ? "Maximized" : "Minimized");

  self.removeSelected = function () {
    vm.board().removeWidget(this);
  };
}

我注意到您的代码有两点:

首先,您用来实例化 Gridster 的选择器在容器 div 而不是 ul 上,它应该包含表示小部件的 li 元素。因此,li 元素被创建为容器 div 的子元素,而不是 ul 元素,Knockout 在触发 beforeremove 时返回报告。现在,beforeremove 回调正在报告正在删除的空白节点,而不是兄弟 li 节点。更新选择器将解决您的部分问题。

其次,在使用您的代码检查 fiddle 时,我发现 ul 元素(定义模板 + foreach 实现)和表示模板内容的 li 元素之间的空格也会导致问题.因此,即使您更正了 Gridster 选择器,您仍然只会看到空白节点在 beforeremove 回调中被报告回来。消除空格似乎可以确保在 beforeremove 回调中报告 li 元素而不是空格。

我不是 Knockout 专家,所以我无法全面解释这是为什么,但是进行这两项更改可以解决您报告的问题。下面是一个 jsfiddle,其中包含这些更改。样式和 Gridster 配置仍然存在一些问题,但小部件将按预期返回并正确删除。

http://jsfiddle.net/PeterShafer/2o8Luyvn/1/

祝您实施顺利。

HTML

<button data-bind='click: add1'> Add 1 </button>
<button data-bind='click: add20'> Add 20 </button>
</button>

<div class="gridster">
<!-- The list.  Bound to the data model list. -->
  <ul data-bind="template: {foreach: board().widgets, afterAdd: board().addGridster, beforeRemove: board().removeGridster}"
      id="board-gridster"><li data-bind="attr: {'id': id, 'data-row': dataRow, 'data-col': dataCol,'data-sizex': datasizex, 'data-sizey': datasizey}"
        class='gs-w'
        style='list-style-type: none; background:#99FF99;'>
      <div data-bind="click: removeSelected"
           style='float:right; cursor: pointer'>
        X
      </div>

      <div data-bind='if: state() === "Minimized"'>
        <span data-bind="style:{ 'backgroundColor': color">
          -
        </span>
      </div>

      <div data-bind='if: state() === "Maximized"'>
        <span data-bind="text: value">
        </span>
      </div>
    </li></ul>
</div>

JS

var vm;

$(function() {
  vm = new MainViewModel();
  ko.applyBindings(vm);
});

function MainViewModel() {
  var self = this;

  self.board = ko.observable(new BoardViewModel());

  self.add1= function() {
    self.board().addRandomWidget();
  };

  self.add20 = function() {
    for(var i = 0; i < 20; i++) {
      self.add1();
    }
  };
};

function BoardViewModel () {
  var self = this;

  // Used for binding to the ui.
  self.widgets = ko.observableArray([]);

  // Initialize the gridster plugin.
  self.gridster = $(".gridster ul").gridster({
    widget_margins : [8, 5],
    widget_base_dimensions : [100, 31],
    extra_rows: 2,
    resize : {
      enabled : false
    }
  }).data('gridster');

  self.cols = self.gridster.cols;
  self.rows = self.gridster.rows;


  /**
   * Used as a callback for knockout's afterAdd function.  This will be called 
   * after a node has been added to the dom from the foreach template.  Here,
   * we need to tell gridster that the node has been added and then set up 
   * the correct gridster parameters on the widget.
   */
  self.addGridster = function (node, index, obj) {
    var widget = $(node);
    var column = widget.attr("data-col");

    console.log('adding: ');
    console.log(node);

    // afterAdd is called one for each html tag.
    // We only want to process it for the main tag, which will have a data-col
    // attribute.
    if (column) {
      // width and height
      var sizeX = obj.datasizex;
      var sizeY = (obj.state() === "Minimized" || obj.state() === "Closed")? 1 : obj.datasizey;

      // add the widget to the next position
      self.gridster.add_widget(widget, sizeX, sizeY);
    }
  };

  /**
   * Used as a callback for knockout's beforeRemove.  Needs
   * to remove node parameter from the dom, or tell gridster
   * that the node should be removed if it is an li. 
   */
  //var hackPrevWidget = null;
  self.removeGridster = function (node, index, widget) {
    // TODO this is never called on the li.  
    console.log("Removing");
    console.log(node);

    // Only including this so that the widget goes
    // away from gridster.  We should not have to 
    // Have this strange hack.  Ideally, we 
    // could check to see if the current node is
    // an li and then remove it from gridster, 
    // but something is preventing it from ever
    // being passed in.  What is happening to this
    // node that causes knockout to lose it?
    //if (widget !== hackPrevWidget) {
    //  self.gridster.remove_widget($('#' + widget.id));
    //} else {
      node.parentNode.removeChild(node);
    //}
    //hackPrevWidget = widget; 
  };


  /**
   * Adds a new widget to the knockout array.
   */
  self.addRandomWidget = function() {
    self.widgets.push(new Widget());
  };

  /**
   * Remove a widget from knockout
   */
  self.removeWidget = function(widget) {
    self.widgets.remove(widget);
  };
};

  var ids = 1;

function Widget(args) {
  var self = this;
  var col, row;

  // We keep an id for use with gridster.  This must be here if we
  // are still using gridster in the widget container.
  self.id = ids++;

  /*------------- Setup size ------------------*/
  self.datasizex = 2;
  self.datasizey = 6;

  /*------------- Setup position ------------------*/
  self.dataRow = 0;
  self.dataCol = 0;

  self.value = ko.observable(Math.random());
  self.state = ko.observable(Math.random() > .5 ? "Maximized" : "Minimized");

  self.removeSelected = function () {
    vm.board().removeWidget(this);
  };
}