问题
In the new Ember.Router
that shipts with Ember 1.0-rc2, is it possible add route in run-time?
回答1:
There is not a supported method of doing this currently. The App.Router.map
call is handled by lines 235-247 of this code: https://github.com/emberjs/ember.js/blob/master/packages/ember-routing/lib/system/router.js
Ember.Router.reopenClass({
map: function(callback) {
var router = this.router = new Router();
var dsl = Ember.RouterDSL.map(function() {
this.resource('application', { path: "/" }, function() {
callback.call(this);
})
});
router.map(dsl.generate());
return router;
}
The map is overwritten every time you call Router.map
as the callback for the previous call to Router.map
is not persisted.
Edit
For better or worse, I've got a pull request in to alter the behavior to allow multiple calls to App.Router.map
. We'll see what happens. You can follow here https://github.com/emberjs/ember.js/pull/2485
Another Edit
I've written a gist to do what my pull request does in userland. This will let you map routes at runtime. Just add this code and then replace your calls to App.Router.map
with the method that I've defined
https://gist.github.com/grep-awesome/5406461
Answer Changing Edit
As of this pull request, you may now call map
multiple times. https://github.com/emberjs/ember.js/pull/2892
回答2:
I see that wmarbut's answer hasn't been accepted, but it is a good one (for me). It seems that his patch is on its way into the Ember release, but until then this is some code that uses his patch. (Don't accept my answer, I'm just happy to have found this.) I'm planning to use it as part of a solution to let content drive navigation. Good question, user1517325 and thanks, wmarbut!
// was an all-in-one router map as Ember likes it
// App.Router.map(function() {
// this.resource("foods", function(){
// this.route("index", {path: "/"});
// });
// this.route("fourOhFour", { path: "*:"});
// });
//wmarbut's workaround until his patch is applied
App.map_routes = [];
App.MapRoutes = function(routes) {
App.map_routes.push(routes);
return App.Router.map(function() {
var route_lamda, _i, _len, _ref;
_ref = App.map_routes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
route_lamda = _ref[_i];
route_lamda.call(this);
}
return true;
});
};
//partial mapping
App.MapRoutes(function() {
this.resource("foods", function(){
});
});
//some more mapping
App.MapRoutes(function() {
this.resource("foods", function(){
this.route("index", {path: "/"});
});
});
//even more mapping
App.MapRoutes(function() {
this.route("fourOhFour", { path: "*:"});
});
回答3:
In the latest release ember.js rc7 it was added the functionality to the Router.map
to allow it to be called multiple times without the map being overwritten. This will allow routes to be added at runtime.
Hope it helps.
来源:https://stackoverflow.com/questions/15921997/ember-router-how-to-add-a-route-in-run-time-in-ember-1-0-rc2