mercredi 22 avril 2015

In an ember model, how can you reference dynamic object keys?

In our application currently we are passing an array of objects from the server side into the model, and each element in the array has a key in it. For instance...

[{name: "dog", sound: "bark", food: "cats"}, {name: "cat", sound: "meow", food: "mouse"}]

In the model this is defined like so...

animals: hasMany(Animal, {key: 'name', embedded: true })

Then if we want the data for the cat, we use the findBy feature to find the one with the name = "cat" like so...

var animalName = "cat";
model.get('animals').findBy('name', animalName);

This works well, there are lots of potential types of 'animal' objects, and we already know what we're looking for.

However I'm curious for other reasons if we can pass this in as a Map from the server, which becomes a JSON object on the client that looks like this...

animals : { "dog" : {sound: "bark", food: "cat"},
            "cat" : {sound: "meow", food: "mouse"}
          }

It seems that in order to do this, in the model code we need to define a "has a" relationship for each potential animal type, which is dynamic and we do not want to hard code all the options here. Is there a way to say animals hasMany animals, but there in a map by name, rather then just an array?




Aucun commentaire:

Enregistrer un commentaire