Ember组件'jQuery可排序的模板问题

Ember component's template issue with jQuery sortable

本文关键字:排序 问题 jQuery 组件 Ember      更新时间:2023-09-26

我正在尝试创建一个简单的Ember组件,该组件封装jQuery UI Sortable插件。不幸的是,当sortable被取消并且模型被手动更新时,我对组件的模板有问题。看起来DOM并没有反映模型的状态。我不知道为什么。

我创建了JS Bin来呈现这个问题。更改项目位置时,应删除组中的第一个项目。不幸的是,它是随机工作的。

这个代码出了什么问题?

这是您的JS Bin可排序组件:

App.MyListComponent = Ember.Component.extend({
  tagName: 'ul',
  didInsertElement() {
    let opts = {};
    opts.update = this.updateList.bind(this);
    this.$().sortable(opts);
  },
  updateList() {
    this.$().sortable('cancel');
    Ember.run.next(() => {
      this.get('content').removeAt(0);
    });
  }
});

然后这是你的JS Bin更新了来自ember ui可排序回购的代码,如下所示:

App.MyListComponent = Ember.Component.extend({
  tagName: 'ul',
  uiOptions: [
    'axis',
    'containment',
    'cursor',
    'cursorAt',
    'delay',
    'disabled',
    'distance',
    'forceHelperSize',
    'forcePlaceholderSize',
    'grid',
    'handle',
    'helper',
    'opacity',
    'placeholder',
    'revert',
    'scroll',
    'scrollSensitivity',
    'scrollSpeed',
    'tolerance',
    'zIndex'
  ],
  destroySortable: Ember.on('willDestroyElement', function() {
    this.$().sortable('destroy');
  }),
  initSortable: Ember.on('didInsertElement', function () {
    let opts = {};
    ['start', 'stop'].forEach((callback) => {
      opts[callback] = Ember.run.bind(this, callback);
    });
    this.$().sortable(opts);
    this.get('uiOptions').forEach((option) => {
      this._bindSortableOption(option);
    });
  }),
  contentObserver: Ember.observer('content.[]', function () {
    Ember.run.scheduleOnce('afterRender', this, this._refreshSortable);
  }),
  move(oldIndex, newIndex) {
    let content = this.get('content');
    let mutate = this.getWithDefault('mutate', true);
    let item = content.objectAt(oldIndex);
    if (content && mutate) {
      content.removeAt(oldIndex);
      content.insertAt(newIndex, item);
    }
    if(!mutate){
      this.attrs.moved(item, oldIndex, newIndex);
    }
  },
  start(event, ui) {
    ui.item.data('oldIndex', ui.item.index());
  },
  stop(event, ui) {
    const oldIndex = ui.item.data('oldIndex');
    const newIndex = ui.item.index();
    this.move(oldIndex, newIndex);
  },
  _bindSortableOption: function(key) {
    this.addObserver(key, this, this._optionDidChange);
    if (key in this) {
      this._optionDidChange(this, key);
    }
    this.on('willDestroyElement', this, function() {
      this.removeObserver(key, this, this._optionDidChange);
    });
  },
  _optionDidChange(sender, key) {
    this.$().sortable('option', key, this.get(key));
  },
  _refreshSortable() {
    if (this.isDestroying) { return; }
    this.$().sortable('refresh');
  }
});

正如你所看到的,与原来的相比,还有很多额外的内容,所以你可以看看你错过了什么,希望这能帮助你。通过ember-cli安装该组件插件可能是个好主意,但也可以先使用ember-observer之类的东西来看看ember-sortable等竞争解决方案。