Reputation: 1811
Typically in Ember, you setup your model:
export default Model.extend({
"name": attr('string'),
"address": attr('string'),
"sports": attr()
})
You then create a form:
{{input value=name}}
{{input value=address}}
{{input value=sports}}
From there you can get the value of the input or set the value:
var name_val = this.get('name');
var address_val = this.get('address');
var sports_val = this.get('sports');
or set a value:
this.set('address','123 Main Street');
How would one create dynamic multidimensional arrays and store them? For example, you want to list out several sports:
{{input type="checkbox" name="baseball" checked=baseball.isChecked}}
{{input type="checkbox" name="football" checked=football.isChecked}}
{{input type="checkbox" name="hockey" checked=hockey.isChecked}}
From there perhaps you want to know given a sport checked, does the user watch that sport, or play that sport? This could be done using a dropdown or more checkboxes. Ultimately, the end result would be this json:
{
'name': 'Matt',
'address': '123 Main Street',
'sports': {
'baseball': 'watch',
'hockey': 'play'
}
}
It seems Ember is easy to setup items one level deep, but what about multi, dynamic values and levels?
Upvotes: 0
Views: 441
Reputation: 2465
In such a scenario, I would recommend using hasMany relationship instead. It would make things more flexible too, for instance if you want to add more attributes associated with the sport you can do so easily:
//user.js
import DS from 'ember-data';
export default Model.extend({
"name": DS.attr('string'),
"address": DS.attr('string'),
"sports": DS.hasMany('sport')
})
//sport.js
import DS from 'ember-data';
export default Model.extend({
"name": DS.attr('string'),
"play": DS.attr('boolean'),
"watch": DS.attr('boolean')
});
Since we want the payload to be embedded, we can use of embedded record mixin:
//serializers/user.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
sports: { embedded: 'always' }
}
});
The default payload with this structure would look like:
{users:[
{
'id':1,
'name': 'Matt',
'address': '123 Main Street',
'sports': [
{'id':1, 'name':'baseball', 'watch':true, 'play':false},
{'id':2, 'name':'hockey', 'watch':true, 'play':true}
]
}
]}
But if you absolutely need the payload to look like what you have, then you might want to dig into serializers (http://emberjs.com/api/data/classes/DS.RESTSerializer.html) , specially "normalize" to feed data to client in the format ember data understands and then "serialize" to alter data to send over to the server in the format you want to store.
Upvotes: 1