Ember Data, how to use registerTransform

╄→гoц情女王★ 提交于 2020-01-22 16:26:12

问题


I've been Googling for a while now, but haven't found any good solution.

The root of the problem is that my records aren't being set to isDirty when using this method:

DS.JSONTransforms.object = {
  deserialize: function(serialized) {
    return Ember.isNone(serialized) ? {} : serialized;
  },
  serialize: function(deserialized) {
    return Ember.isNone(deserialized) ? {} : deserialized;
  }
}

From what I gather this is an old method that apparently still works, since it handles the JSON objects I'm throwing at it, but it's not setting my records to isDirty when making edits.

What you now should be using is registerTransform on your adapter (according to this https://github.com/emberjs/data/issues/517). But my custom transform isn't being registered, so I guess I'm putting it at the wrong place (same place as my previous JSONTransforms).

DS.RESTAdapter.registerTransform('object', {
  deserialize: function(serialized) {
    return Em.none(serialized) ? {} : serialized;
  },
  serialize: function(deserialized) {
    return Em.none(deserialized) ? {} : deserialized;
  }
});

Any one have knowledge to share about this?


回答1:


The issue with isDirty is not because you're not using registerTransform, the behavior will be the same.

For now, Ember Data does not support object attributes, one of the difficulty is in fact to observe the changes to set the isDirty flag.

There is an open issue for this that you can track on github.

A workaround would be to declare the nested objects as proper DS.Model and set an embedded relationship between them.

For the example, let's say you have a date object sended with a post :

{post: {
  id: 12
  title: "EmberData accept object attributes, you do not need this anymore !!"
  date: {
    day: "01"
    month: "03"
    year: "2013"
  }
}}

You will declare the model as following :

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  date: DS.belongsTo('App.PostDate')
});

App.PostDate = DS.Model.extend({
  post: DS.belongsTo('App.Post'),
  day: DS.attr('string'),
  month: DS.attr('string'),
  year: DS.attr('string'),
});

And add a mapping in your adapter :

DS.RESTAdapter.map('App.Post',{
  date:{
    embedded:'always'
  }
})

See this answer for more detail about the embedded mapping option.




回答2:


I disagree. I think its inefficient and overly complex to have to have extra calls for all your child relationships/records. I found a work around for this. Add a field for 'last_updated' and after you change the value of your nested stuff, just update the last_updated to the current time, that will trigger the 'isDirty' flag and allow you to update...



来源:https://stackoverflow.com/questions/14695370/ember-data-how-to-use-registertransform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!