当用Ember-Data保存时,所有项目上的数据复制

Data duplicating on all items when saving with Ember-Data

本文关键字:项目 数据 复制 Ember-Data 保存 当用      更新时间:2023-09-26

我有一个页面,用户在其中编辑上传的照片,并使用Ember-Data在模型上为单个照片应用标记。但是,在保存到控制器上并过渡到列出所有照片的页面后,标签将出现在所有项目上,并取代之前存在的任何标记。如果我重新打开页面,标签根本没有保存。

我不太确定是什么导致了这个问题。如有任何帮助,不胜感激。

//The photo model
App.Photo = DS.Model.extend({
  title: attr(),
  description: attr(),
  image: attr(),
  width: attr(),
  height: attr(),
  important_top: attr(),
  important_left: attr(),
  important_bottom: attr(),
  important_right: attr(),
  created: attr('date'),
  authors: hasMany('author'),
  app_data: {
    tags: []
  },
  imageURL: function() {
    return document.location.origin + '/media/' + this.get('image');
  }.property('image'),
});

// Photo edit route
App.PhotoseditRoute = Ember.Route.extend({
  model: function() {
    this.store.find('photo');
    // Populate model with photos from the lowest upload ID to higest.
    return this.store.filter('photo', function(image){
      return image.get('id') >= App.Upload.uploadedImages[0]; // Get data from uploader
    });
  },
  activate: function() {
    $('#page-title').text('Edit Photos');
  },
});

// Photo Edit Controller
App.PhotoseditController = Ember.ObjectController.extend({
    parsedTags: function() {
      // Get tags from the view's input field
      var tagData = this.get('app_data').tags;
      // Convert tags to an array
      return tagData.join(',');
    }.property('app_data'),
    // Watch parsedTags and apply array to model when converted
    parsedDataChanged: function() {
      Ember.run(this, function() {
        this.get('app_data').tags = this.get('parsedTags').split(',');
      });
    }.observes('parsedTags'),
  actions: {
    save: function() {
      var that = this;
      that.get('model').save().then(function(success) {
        that.transitionToRoute('photos');
      });
    }
  }
});
// Photo edit template
<h2>Edit Photo Meta Data</h2>
<button {{action 'save'}} style="float:right;">Save All</button>
<table>
  <thead>
    <tr>
      <th></th>
      <th>Title</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    {{#each object in content itemController='photosedit'}}
    <tr>
      <td><img {{bind-attr src="imageURL"}} width="200" /></td>
      <td>{{input title valueBinding="title"}}</td>
      <td>{{input description valueBinding="description"}}</td>
      <td>{{input parsedTags valueBinding="parsedTags"}}</td>
    </tr>
    {{else}}
    <tr>
      <td colspan="6">No photos yet.</td>
    </tr>
    {{/each}}
  </tbody>
</table>

问题来自于您声明app_data的方式。该变量将在App.Photo的所有实例中共享,这解释了为什么您看到所有照片都获得相同的标签。

您可以通过以不同的方式初始化属性来解决这个问题:

App.Photo = DS.Model.extend({
  init: function() {
    this._super();
    this.app_data = { tags: [] };
  }
});
不是

App.Photo = DS.Model.extend({
  app_data = { tags: [] }
});

请参阅此JsBin以获得突出显示问题和解决方案的示例http://emberjs.jsbin.com/wawoq/3

当您调用save()并从那里进行跟踪时,您需要检查是否使用正确的数据调用了存储。

除此之外,parsedTags和parseddatachchanged似乎是相互引用的