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', })
The websocket method:
App.io.emit('node', {node: hash});
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..
In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.
In Ember Data, serializers format the data sent to and received from the backend store. By default, Ember Data serializes data using the JSON:API format. If your backend uses a different format, Ember Data allows you to customize the serializer or use a different serializer entirely.
Ember Data ships with 3 Serializers. The JSONAPISerializer is the default serializer and works with JSON API backends.
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); } });
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);
You can get a plain JS object (or hash) from an Ember.Object
instance by calling getProperties()
with a list of keys.
If you want it as a string, you can use JSON.stringify()
.
For example:
var obj = Ember.Object.create({firstName: 'Erik', lastName: 'Bryn', login: 'ebryn'}), hash = obj.getProperties('firstName', 'lastName'), // => {firstName: 'Erik', lastName: 'Bryn'} stringHash = JSON.stringify(hash); // => '{"firstName": "Erik", "lastName": "Bryn"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With