Ember.js Controller Hierarchy part 5
Ember.js Controller Hierarchy part 5: session property, register(),and inject()
by jdcravens
HTML
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/ember-latest.js"></script>
<script src="http://builds.emberjs.com/canary/ember-data.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<h3>Ember.js Controller Hierarchy part 5</h3>
<p>This sets the session property of every controller instance to a singleton instance of App.Session. register can register controllers, models, views, or an arbitrary type like session as above. inject, in turn, can inject onto all instances of a given class, or all instances of a given type. inject('model', 'session', 'session:current') injects a session property with the session:current instance onto all models. inject('view:index', 'session', 'session:current') injects a session property with the session:current instance onto instances of the IndexView.</p>
<b>register and inject are very powerful tools, and easy to abuse. I usually use them as a tool of last resort- or for logic that does not fit smoothly into the Ember MVC pattern.</b>
<script type="text/x-handlebars" id="index">
<hr>
<p>From index, session: {{session}}</p>
<div>{{render 'navigation'}}</div>
<div>{{render 'childView'}}</div>
</script>
<script type="text/x-handlebars" id="navigation">
<hr>
<p>From navigation, session: {{session}}</p>
</script>
<script type="text/x-handlebars" id="childView">
<hr>
<p>From childView, session: {{session}}</p>
</script>
JavaScript
var App = Em.Application.create();
var App = Em.Application.create({
ready: function(){
this.register('session:current', App.Session, {singleton: true});
this.inject('controller', 'session', 'session:current');
}
});
App.Session = Em.Object.extend();