Search code examples
javascriptember.jsrouterember-router

Force route to instantiante new controller/view pair instead of changing model


I would like to display a certain controller/view pair multiple times simultaneously. Problem is that the route changes the model on the current controller instead of creating a new one.

Is it possible to force a route to instantiate new controller? I've tried messing with the callbacks and hooks in Ember.Route but I can't find any way to make it behave like this.


Solution

  • If you want to display multiple models simultaneously, it seems like having the route point to a single model that changes doesn't map well to what you're trying to do. The router was not designed to add additional views to a display unless you use nested routes. You could try overriding the renderTemplate hook in your route and use render() to specify which controller is used, but that doesn't help you with multiple controller/view pairs being displayed simultaneously.

    Instead, I would try using one of the ways to specify a custom controller. When you have a collection of things to display, the simplest way is with the #each helper in your template.

    {{#each product in products itemController='myControllerName'}}
    

    If you'd like to specify a custom view class, you can do that also.

    {{#each product in products itemController='myControllerName' itemViewClass='App.MyView'}}
    

    Depending on what you're trying to do, an alternative approach to getting a context that gets a new instance every time is by creating a component. This is more heavy weight, though, and you would probably need to refactor some of your code, moving the controller logic into the component.