簡體   English   中英

你如何序列化Ember對象?

[英]How do you serialise Ember objects?

我需要使用localStorage來存儲一些Ember對象。 我注意到Ember對象具有名稱為__ember1334992182483屬性。 當我在Ember對象上調用JSON.stringify()時,這些__ember*屬性不會被序列化。 為什么是這樣? 我不是說我要序列化這些屬性。 我只是好奇它們究竟是什么以及它們是如何實現的,以至於它們不是序列化的。

我正在使用cycle.js( https://github.com/douglascrockford/JSON-js/blob/master/cycle.js )將包含重復引用的數據結構編碼為可用於重建原始數據的字符串結構。 它可以讓你這樣做:

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

對於Ember對象,我可以做同樣的事情,但我還需要將反序列化的對象傳遞給Ember.Object.create()因為它們被反序列化為純JavaScript對象。

這是序列化/反序列化Ember對象的最佳方法嗎? 有推薦的技術嗎?

對於序列化和反序列化,您可以按照這一行做一些事情,請參閱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() );​

更新 :還看看類似的問題Ember模型到json

我會使用ember-data並為此編寫數據存儲適配器。

我有:

  • 固定和簡化的代碼
  • 增加了循環參考預防
  • 增加了對價值的使用
  • 刪除了空組件的所有默認屬性

     //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