这就是我最终做的事情。它有效,但似乎太复杂了,所以我怀疑它存在根本缺陷。非常欢迎任何更正和/或改进。
这是创建导航栏的视图:
<script type="text/x-handlebars" data-template-name="nav">
<ul class="nav">
{{#each navs}}
<li {{bindAttr class="isActive:active"}}><a href="#" {{action select link}}> {{title}}</a></li>
{{/each}}
</ul>
</script>
这是驱动它的大量代码:)
App.ApplicationController = Ember.Controller.extend({
active: 'index'
});
App.ApplicationRoute = Ember.Route.extend({
setupController: function(){
var active = this.controllerFor('application').get('active');
this.controllerFor('nav').set('model',{
active:'index',
navs: [
{ link:"index", title:'Toad', isActive: active === 'index' },
{ link:"lunches", title:'Lunches', isActive: active === 'lunches' },
{ link:"people", title:'People', isActive: active === 'people' }
]
});
},
events: {
select: function (item) {
var nav = this.controllerFor('nav');
var app = this.controllerFor('application');
app.set('active',item);
var active = app.get('active');
var navs = nav.get('navs');
new_navs = [];
for (var i = navs.length - 1; i >= 0; i--) {
new_navs[i] = { link: navs[i].link, title: navs[i].title, isActive: active === navs[i].link} ;
};
nav.set('navs',new_navs);
this.transitionTo(item);
}
}
});
App.NavController = Ember.ObjectController.extend({
});
// Routes
App.Router.map(function() {
this.route("people");
this.route("lunches");
});
App.PeopleRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.send('select','people');
controller.set('people', App.People.find());
},
});
App.LunchesRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.send('select','lunches');
controller.set('lunches', App.Event.find());
},
});
拜托,做你最坏的事,把它撕开,把我纠正过来!