red*_*ory 3 ember.js ember-router
我有一个看起来像这样的链接
index.html#/calendar/year/month
Run Code Online (Sandbox Code Playgroud)
这是我设置路线的方式:
App.Router.map(function() {
this.resource('calendar', {path: 'calendar/:currentYear/:currentMonth'});
});
App.CalendarRoute = Ember.Route.extend({
model: function (params) {
var obj = {
weeks: calendar.getDaysInMonth(params.currentMonth, params.currentYear),
currentMonth: params.currentMonth,
currentYear: params.currentYear
};
return obj;
},
setUpController: function(controller, model) {
controller.set('content', model);
}
});
Run Code Online (Sandbox Code Playgroud)
我可以通过这样做:
var currentMonth = this.get('content.currentMonth');
var nextMonth = parseInt(currentMonth)+1;
var route = '#/calendar/'
var year = this.get('content.currentYear');
window.location.href= route + year + '/' + nextMonth;
Run Code Online (Sandbox Code Playgroud)
但我想改用路由器。
我试过:
var router = this.get('target');
router.transitionTo('#calendar/'+year + '/' + nextMonth);
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
未捕获的错误:断言失败:找不到路由#calendar/2013/5
我也试过:
var router = this.get('target');
router.transitionTo('calendar/'+year + '/' + nextMonth);
Run Code Online (Sandbox Code Playgroud)
但这也给了我一个错误:
未捕获的错误:断言失败:未找到路线日历/2013/5
编辑:在上面显示我的路由
与我在评论中所说的相反,这实际上可以在不需要嵌套路由的情况下完成,使用Route#serialize.
我用类似于你描述的场景制作了这个小提琴(demo here):
在应用程序中,我存储了月份和年份参数
window.App = Ember.Application.create({
title: 'Cool App',
calendar: {
month: new Date().getMonth()+1,
year: new Date().getFullYear()
}
});
Run Code Online (Sandbox Code Playgroud)
定义路由
App.Router.map(function() {
this.route("home");
this.resource('calendar', { path: 'calendar/:year/:month'});
});
Run Code Online (Sandbox Code Playgroud)
在日历路由中,我添加了serialize方法,将属性obj转换为应用程序,然后我连接到第 3 方库setupController以获取days属性并设置其内容。
App.CalendarRoute = Em.Route.extend({
activate: function() {
$(document).attr('title','Events')
},
serialize: function(obj) {
return {
year: obj.year, month: obj.month
}
},
setupController: function(controller, model) {
var obj = {
days: calendar.getDaysInMonth(model.month, model.year),
year: model.year,
month: model.month
};
controller.set('content', obj);
}
});
Run Code Online (Sandbox Code Playgroud)
在 Handlebars 中,使用{{linkTo}}助手,我将calendar在我的App类中定义的属性作为参数传递:
{{#linkTo calendar App.calendar tagName="li"}}
<a {{bindAttr href="view.href"}}>
Calendar
</a>
{{/linkTo}}
Run Code Online (Sandbox Code Playgroud)
这将生成一个链接到 ~/#/calendar/2013/4