I’m experimenting with routing in ember at the moment, and have a working example. The problem is, I’m a bit confused WHY it works. Currently this route just has 2 simple views. Here is the code:
App = Em.Application.create();
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: '/',
redirectsTo: 'home' //when hitting the base URL, redirect to home
}),
home: Ember.Route.extend({
route: '/home',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('home');
}
}),
about: Ember.Route.extend({
route: '/about',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('about');
}
})
})
});
//Main controller + view
App.ApplicationController = Ember.Controller.extend({});
App.ApplicationView = Ember.View.extend({
templateName: 'application',
goHome: function(){
App.router.transitionTo('home');
},
goAbout: function(){
App.router.transitionTo('about');
}
});
// Home page
App.HomeView = Ember.View.extend({
templateName: 'home'
})
// About page
App.AboutController = Ember.Controller.extend({
numWidgets: 45
})
App.AboutView = Ember.View.extend({
numWidgetsBinding: 'App.aboutController.numWidgets',
templateName: 'about'
})
App.initialize();
In my HTML I just have a couple of really simple templates with the names “application”, “home” and “about”.
So, it all works, and looks very similar to all the examples floating about on the net. Great! But I’m confused about how it seems I have several things instantiated for me, without me asking to do it. Is this correct?
For example:
How is it creating an instance of ApplicationController?
In the connectOutlets functions, it’s looking for a controller called “applicationController”. I never created anything called “applicationController” (with lower-case “a”), I just extended a controller and called it “ApplicationController” (with a capital “A”). Why does this work?
How is it creating an instance of AboutController?
I did a simple test binding between the “about” page view and controller. In the view, I am binding with the variable ‘App.aboutController.numWidgets’. I never called App.AboutController.create(). So how is there an instance of this ready for me to talk to? Again, it has a lower case letter (“aboutController”). All I ever did was extend a controller (and named it with a capital letter – “AboutController”)
A little explanation would be great, as like any normal developer, I feel that using code where you dont know why it’s working is crazy!
App.initialize();does all the instantiation and injection stuff :), based on strong naming conventions: Ember naming / capitalization convention. When you call xxxController.connectOutlet(options), the option has is also conventional, see Confusion about naming conventions in emberjsHope that helps.
EDIT: With the latest master, you don’t have to call App.initialize() manually. The application is auto-initialized when all is ready 🙂