使用Ember-Data保存时,所有项目上的数据都会重复

时间:2014-03-12 20:57:44

标签: javascript ember.js ember-data

我有一个页面,用户可以使用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>

2 个答案:

答案 0 :(得分:3)

问题来自您声明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

答案 1 :(得分:1)

当您调用save()并从那里追溯时,您需要检查是否使用正确的数据调用了商店。

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