mercredi 25 mars 2015

Dynamic controllers in Ember.js

I want to make some dynamic controllers based on the top-level keys of a JSON object where the second level keys become variables for the view. Is this possible?


E.g.



App.dat = { "First": {Var1: "x", Var2: "y"}, "Second": {Var3: "z"}}


I then want to have a FirstController, SecondController, etc. created automatically and then be able to access {{Var1}}, {{Var2}} and {{Var3}} in my view.


The routes work fine:



App.Router.map(function() {
this.route('data');
for(var key in App.dat) {
this.route(key);
}
});


But I can't get the controllers to work. The closest I came was with some hacky eval code:



for(var key in App.dat) {
console.log("App." + key + "Controller = Ember.Route.extend();");
eval("App." + key + "Controller = Ember.Route.extend();");
Ember.$.each(eval("App.dat."+key), function(kkey,v) {
console.log("App." + key + "Controller." + kkey + " = '" + v + "';");
eval("App." + key + "Controller." + kkey + " = '" + v + "';");
});
}


That results in the following evaluations:



App.FirstController = Ember.Route.extend();
App.FirstController.Var1 = "x";
App.FirstController.Var2 = "y";
App.SecondController = Ember.Route.extend();
App.FirstController.Var2 = "z";


But I'm clearly missing something because I can't access {{x}},{{y}} or {{z}} from the view. I am aware the correct way to instantiate variables for the view is with a constructor object like:



App.FirstController = Ember.Route.extend({Var1: "x", Var2: "y"});


But that isn't practical and I can't figure out where the constructor object gets stored.


Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire