我需要使用 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
对于 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 model to json
关于serialization - 你如何序列化 Ember 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257144/