Creation of Controllers at runtime like views

So… a bit of confusion on creating controllers at runtime (since creating views is trivial).

I’ve seen this:

But that isn’t quite right either, as that controller a) is an orphan and b) has no container/isn’t really part of anything. What i’m trying to do:

Route
  Controller
    View
       View created in javascript (not in a template view {{view helper}} etc)
          view created in javascript --- this guy, i'd like to have a "controller" for.

Is there a way to create a view/controller pair, in javascript, at runtime, that “works” or is this just simply not something I should do?

(and thus, the problem, that if I ended up with 50 little “subviews” or widgets, technically 100% of all their functionality and model/pseudo model gets handled by one GIANT GIANT controller way way up the stack)

Thoughts?

I’m sure it’s possible, but I would shy away from it. Controllers and routes are singletons for a reason; you really shouldn’t be storing any kind of persistent state in them, that’s what models are for.

My suggestion, in your case with 3 nested views, would be to create 3 nested routes, so they all have their own controller. And they’ll have access to each other via the parentView property.

Yeah, i’d do nested routes if the use case in any way, shape or form allowed for it but sadly it does not :smile: (simply imagine a dashboard with 50 widgets on it… that are 10 different types (5 instances each) that have very very unique action handling requirements.

In the end, the url is still just dashboard/:id basically, just happens to have lots of custom views in it etc.

Just trying to avoid “dashboardController” from being a monster :wink:

It sounds like you should use the render helper with your dashboard template to show each widget.

{{render}} does several things:

When no model is provided it gets the singleton instance of the corresponding controller

When a model is provided it gets a unique instance of the corresponding controller

Renders the named template using this controller

Sets the model of the corresponding controller

Yeah… i’d go that route if the view generator was happening in handlebars templates.

But since it is happening 100% on the fly in javascript code that technique (a good one) isn’t available.

I see what you are saying. Perhaps look at how the render helper instantiates the controller and use that method:

// if model
if (length > 2) {
  var factory = container.lookupFactory(controllerFullName) ||
                Ember.generateControllerFactory(container, controllerName, context);

  controller = factory.create({
    model: context,
    parentController: parentController,
    target: parentController
  });

} else {
  controller = container.lookup(controllerFullName) ||
               Ember.generateController(container, controllerName);

  controller.setProperties({
    target: parentController,
    parentController: parentController
  });
}