删除内容时更新ember.js视图

时间:2013-07-12 18:30:45

标签: ember.js

我正在尝试使用Ember.js实现拖放。除了让视图在最后更新外,我还能正常工作。这是一个jsfiddle:

http://jsfiddle.net/rsaNy/

如果您从源列表中拖动某些内容并将其放入dest div中,我希望将其添加到显示中。我设置的两个警报确认数据结构实际上正在更新,但更新未反映在视图中。我该如何解决这个问题?这是代码。

DragNDrop = Ember.Namespace.create();

DragNDrop.cancel = function(event) {
    event.preventDefault();
    return false;
};

App = Ember.Application.create();

testItems =
  [ { name: "Alpha" } ,
    { name: "Bravo" } ,
    { name: "Charlie" } ];

App.SourceItemView = Ember.View.extend({
  templateName: 'sourceItem',
  tagName: 'li',
  attributeBindings: 'draggable',
  draggable: 'true',
  dragStart: function(event) {
      var dataTransfer = event.originalEvent.dataTransfer;
      var msg = this.get('content');
      dataTransfer.setData('text', JSON.stringify(msg));
  }
});

App.SourceView = Ember.View.extend({
  templateName: 'source',
  tagName: 'div',
  classNames: ['well']
});

App.DestView = Ember.View.extend({
  templateName: 'dest',
  tagName: 'div',
  classNames: ['well'],
  dragEnter: DragNDrop.cancel,
  dragLeave: DragNDrop.cancel,
  dragOver: DragNDrop.cancel,
  drop: function(event) {
      var c = this.get('content');
      var fieldStr = event.originalEvent.dataTransfer.getData('text');
      alert(fieldStr);
      c.push(JSON.parse(fieldStr));

      var str = '';
      for (var i = 0; i < c.length; i++) {
        str += c[i].name+' ';
      }
      alert(str);

      return true;
  }
});

App.IndexController = Ember.ObjectController.extend({
  content: { source: testItems,
             dest: [{name: "Delta"}] }
});

1 个答案:

答案 0 :(得分:3)

您需要使用Ember Array pushObject() method代替push()。这允许Ember跟踪其绑定系统的数据更改,这是视图知道更新自身的方式。同样必须始终使用get()set()

drop: function(event) {
      var c = this.get('content');
      var fieldStr = event.originalEvent.dataTransfer.getData('text');
      alert(fieldStr);
      c.pushObject(JSON.parse(fieldStr));
      //...

Here is the working JSFiddle