I am using a json file pulled from the server to configure my website, and to tell each page what it's title is. The json file looks like this:
[{"route": "student", "title": "Student Info Page"}, {"route": "payments", "title": "Payments and Pricing"}, {"route": "policy", "title": "Mine"}, {"route": "biography", "title": "About Me"}]
which is used to create a navigation bar with this code:
App.MenuController = Ember.ArrayController.create();
$.get('config.json', function(data) {
App.MenuController.set('content', data);
});
which is then used in the template:
{{#each App.MenuController}}
{{#varLink route this}}{{title}}{{/varLink}}
{{/each}}
All of this works great so far.
So here's my question: I want the route mapping done with App.Router.map
to be done programatically, using this json object to determine which routes should exist.
How on earth should I do this? I've hunted around the documentation, and then tried this:
$.get('config.json', function(data) {
App.MenuController.set('content', data);
for (var i = 0; i < data.length; i++) {
App.Router.map(function(){
var r = data[i].route;
console.log(r);
this.route(r);
});
}
});
which gives the following console readout:
student app.js:9
payments app.js:9
policy app.js:9
biography app.js:9
Assertion failed: The attempt to linkTo route 'student' failed. The router did not find 'student' in its possible routes: 'index' ember.js:361
Uncaught Error: There is no route named student.index ember.js:23900
I have used this to create the routes dynamically:
App = Ember.Application.create();
App.MenuController = Ember.ArrayController.create();
App.deferReadiness();
simulateAjax(function(data) {
App.MenuController.set("content", data);
App.Router.map(function() {
var router = this;
data.forEach(function(item) {
router.route(item.route);
});
});
App.advanceReadiness();
});
simulateAjax
is just a function that simulate an ajax call to the server.
App.deferReadiness();
and App.advanceReadiness();
delay the application startup, so you don't have the effect of the screen blink, because of the update of new added routes. Since our application ready is: when the routes are created, not document ready.
And here is a demo
link-to
helper support dynamic routing, using a object and path.
But at the moment its needed to use ENV.HELPER_PARAM_LOOKUPS = true
.
With this, we don't need to create a custom linkTo
to handle dynamic path, like the first demo ;)
New demo
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