hek*_*ran 6 serialization deserialization ember.js
我需要使用localStorage来存储一些Ember对象.我注意到Ember对象具有名称类似的属性__ember1334992182483.当我调用JSON.stringify()Ember对象时,这些__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
Run Code Online (Sandbox Code Playgroud)
对于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() );?
Run Code Online (Sandbox Code Playgroud)
更新:还看看类似的问题Ember模型到json