Data-Driven Routing Menu in Ember (Part 2)
This is like the previous version, except that it uses ApplicationRouter.
by Malkyne
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0-rc.1/ember.min.js"></script>
<script type="text/x-handlebars" data-template-name="application">
{{render menu}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="menu">
<ul class = "menu">
{{#each item in content}}
<li>
<a {{action select item}} {{bindAttr class = "item.classNames"}}>
{{item.label}}
</a>
</li>
{{/each}}
</ul>
<br/>
<hr/>
</script>
<script type="text/x-handlebars" data-template-name="detail">
<h1>Page: {{content.label}}</h1>
<p>{{content.info}}</p >
</script>
CSS
h1 {
font-size: large;
font-weight: bold;
margin-bottom: 5px;
margin-top: 5px;
}
ul.menu > li {
display: block;
float: left;
margin-right: 20px;
margin-top: 5px;
margin-left: 5px;
cursor: pointer;
}
ul.menu > li > a {
cursor: pointer;
}
.menu-item {
font-weight: bold;
}
.apple {
color: #FF0000;
}
.orange {
color: #FF6600;
}
.grape {
color: #990099;
}
JavaScript
window.App = Em.Application.create();
App.ApplicationController = Em.Controller.extend({});
App.ApplicationView = Em.View.extend({
templateName: 'application'
});
App.initialize();
App.menuData = [
Em.Object.create({
route: 'apples',
label: 'Apples',
classNames: 'menu-item apple',
info: "This is a page about apples."
}),
Em.Object.create({
route: 'oranges',
label: 'Oranges',
classNames: 'menu-item orange',
info: "This is a page about oranges."
}),
Em.Object.create({
route: 'grapes',
label: 'Grapes',
classNames: 'menu-item grape',
info: "This is a page about grapes."
})];
App.MenuController = Em.ArrayController.extend({
content: App.menuData
});
App.Router.map(function () {
App.menuData.forEach(function (item) {
this.route(item.route);
}, this);
});
App.ApplesRoute = Em.Route.extend({
setupController: function (controller) {
controller.set('content', App.menuData[0]);
},
renderTemplate: function () {
this.render('detail');
}
});
App.OrangesRoute = Em.Route.extend({
setupController: function (controller) {
controller.set('content', App.menuData[1]);
},
renderTemplate: function () {
this.render('detail');
}
});
App.GrapesRoute = Em.Route.extend({
setupController: function (controller) {
controller.set('content', App.menuData[2]);
},
renderTemplate: function () {
this.render('detail');
}
});
App.ApplicationRoute = Em.Route.extend({
events: {
select: function (item) {
this.transitionTo(item.route);
}
}
});