Ember模型到json [英] Ember model to json
问题描述
我正在寻找一种将Ember对象转换为json字符串的有效方式,以便在下面的websocket消息中使用它。
I am looking for an efficient way to translate my Ember object to a json string, to use it in a websocket message below
/*
* Model
*/
App.node = Ember.Object.extend({
name: 'theName',
type: 'theType',
value: 'theValue',
})
websocket方法:
The websocket method:
App.io.emit('node', {node: hash});
哈希应该是节点的json表示。 {name:thename,type:theType,..}
必须有一个快速的onliner来做这个..我不想手动,因为我有很多属性,他们可能会改变..
hash should be the json representation of the node. {name: thename, type: theType, ..} There must be a fast onliner to do this.. I dont want to do it manualy since i have many attributes and they are likely to change..
推荐答案
如上所述,您可以从ember-runtime/lib/core.js#inspect 函数来获取对象的关键字,请参阅 http://jsfiddle.net/pangratz666/UUusD/
As stated you can take inspiration from the ember-runtime/lib/core.js#inspect function to get the keys of an object, see http://jsfiddle.net/pangratz666/UUusD/
App.Jsonable = Ember.Mixin.create({
getJson: function() {
var v, ret = [];
for (var key in this) {
if (this.hasOwnProperty(key)) {
v = this[key];
if (v === 'toString') {
continue;
} // ignore useless items
if (Ember.typeOf(v) === 'function') {
continue;
}
ret.push(key);
}
}
return this.getProperties.apply(this, ret);
}
});
注意,由于提交 1124005 - 在 ember-latest.js
中可用,在下一个版本中,您可以通过 ret
数组直接到 getProperties
,所以 getJson
函数的返回语句看起来像这个:
Note, since commit 1124005 - which is available in ember-latest.js
and in the next release - you can pass the ret
array directly to getProperties
, so the return statement of the getJson
function looks like this:
return this.getProperties(ret);
这篇关于Ember模型到json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!