简体   繁体   English

你如何序列化Ember对象?

[英]How do you serialise Ember objects?

I need to use localStorage to store some Ember objects. 我需要使用localStorage来存储一些Ember对象。 I notice that Ember objects have properties with names like __ember1334992182483 . 我注意到Ember对象具有名称为__ember1334992182483属性。 When I call JSON.stringify() on Ember objects, these __ember* properties are not serialised. 当我在Ember对象上调用JSON.stringify()时,这些__ember*属性不会被序列化。 Why is this? 为什么是这样? I'm not saying that I want to serialize those properties. 我不是说我要序列化这些属性。 I am just curious about what exactly they are and how they are implemented such that they are not serialised. 我只是好奇它们究竟是什么以及它们是如何实现的,以至于它们不是序列化的。

I am using cycle.js ( https://github.com/douglascrockford/JSON-js/blob/master/cycle.js ) to encode my data structures that contain duplicate references into a string that can be used for reconstructing the original data structures. 我正在使用cycle.js( https://github.com/douglascrockford/JSON-js/blob/master/cycle.js )将包含重复引用的数据结构编码为可用于重建原始数据的字符串结构。 It lets you do this: 它可以让你这样做:

a = {a:1}
b = {b:1}
c = [[a, b], [b, a]]

foo = JSON.stringify(JSON.decycle(c))  // "[[{'a':1},{'b':1}],[{'$ref':'$[0][1]'},{'$ref':'$[0][0]'}]]"
JSON.retrocycle(JSON.parse(foo))  // reconstruct c

For Ember objects I can do the same thing, but I also need to pass the deserialised objects into Ember.Object.create() because they are deserialised as plain JavaScript objects. 对于Ember对象,我可以做同样的事情,但我还需要将反序列化的对象传递给Ember.Object.create()因为它们被反序列化为纯JavaScript对象。

Is this the best way to serialise/deserialise Ember objects? 这是序列化/反序列化Ember对象的最佳方法吗? Is there a recommended technique for this? 有推荐的技术吗?

For serialization and deserialization you could do something along this lines, see http://jsfiddle.net/pangratz666/NVpng/ : 对于序列化和反序列化,您可以按照这一行做一些事情,请参阅http://jsfiddle.net/pangratz666/NVpng/

App.Serializable = Ember.Mixin.create({
    serialize: function() {
        var propertyNames = this.get('propertyNames') || [];
        return this.getProperties(propertyNames);
    },

    deserialize: function(hash) {
        this.setProperties(hash);
    }
});

App.Person = Ember.Object.extend(App.Serializable, {
    propertyNames: 'firstName title fullName'.w(),
    fullName: function() {
        return '%@ %@'.fmt(this.get('title'), this.get('firstName'));
    }.property('firstName', 'title')
});

var hansi = App.Person.create({
    firstName: 'Hansi',
    title: 'Mr.'
});

// { firstName: 'hansi', title: 'Mr.', fullName: 'Mr. Hansi' }
console.log( hansi.serialize() );

var hubert = App.Person.create();
hubert.deserialize({
    firstName: 'Hubert',
    title: 'Mr.'
});
console.log( hubert.serialize() );​

UPDATE : Also have a look at the similar question Ember model to json 更新 :还看看类似的问题Ember模型到json

我会使用ember-data并为此编写数据存储适配器。

I have: 我有:

  • fixed and simplified code 固定和简化的代码
  • added circular reference prevention 增加了循环参考预防
  • added use of get of value 增加了对价值的使用
  • removed all of the default properties of an empty component 删除了空组件的所有默认属性

     //Modified by Shimon Doodkin //Based on answers of: @leo, @pangratz, @kevin-pauli, @Klaus //http://stackoverflow.com/questions/8669340 App.Jsonable = Em.Mixin.create({ getJson : function (keysToSkip, visited) { //getJson() called with no arguments, // they are to pass on values during recursion. if (!keysToSkip) keysToSkip = Object.keys(Ember.Component.create()); if (!visited) visited = []; visited.push(this); var getIsFunction; var jsonValue = function (attr, key, obj) { if (Em.isArray(attr)) return attr.map(jsonValue); if (App.Jsonable.detect(attr)) return attr.getJson(keysToSkip, visited); return getIsFunction?obj.get(key):attr; }; var base; if (!Em.isNone(this.get('jsonProperties'))) base = this.getProperties(this.get('jsonProperties')); else base = this; getIsFunction=Em.typeOf(base.get) === 'function'; var json = {}; var hasProp = Object.prototype.hasOwnProperty; for (var key in base) { if (!hasProp.call(base, key) || keysToSkip.indexOf(key) != -1) continue; var value = base[key]; // there are usual circular references // on keys: ownerView, controller, context === base if ( value === base || value === 'toString' || Em.typeOf(value) === 'function') continue; // optional, works also without this, // the rule above if value === base covers the usual case if (visited.indexOf(value) != -1) continue; json[key] = jsonValue(value, key, base); } visited.pop(); return json; } }); /* example: DeliveryInfoInput = Ember.Object.extend(App.Jsonable,{ jsonProperties: ["title","value","name"], //Optionally specify properties for json title:"", value:"", input:false, textarea:false, size:22, rows:"", name:"", hint:"" }) */ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM