我正在为我的应用构建一个简单的每周日历组件,而我正在努力寻找创建周导航的方法。这是我到目前为止所做的:
/week-view/component.js
import Ember from 'ember';
export default Ember.Component.extend({
firstDay: moment().startOf('week'),
days: Ember.computed('firstDay', function() {
let firstDay = this.get('firstDay').subtract(1, 'days');
let week = [];
for (var i = 1; i <= 7; i++) {
var day = firstDay.add(1, 'days').format('MM-DD-YYYY');
week.push(day);
}
return week;
}),
actions: {
currentWeek() {
this.set('firstDay', moment().startOf('week'));
},
previousWeek() {
this.set('firstDay', moment().startOf('week').subtract(7, 'days'));
},
nextWeek() {
this.set('firstDay', moment().startOf('week').add(7, 'days'));
}
}
});
/week-view/template.hbs
<button {{action "previousWeek"}}>previous</button>
<button {{action "currentWeek"}}>current week</button>
<button {{action "nextWeek"}}>next</button>
<ul>
{{#each days as |day|}}
<li>{{day}}</li>
{{/each}}
</ul>
目前它只能在一周之前导航,在本周之后导航一次。任何想法如何使这项工作无限数周非常感谢。提前谢谢。
答案 0 :(得分:1)
我认为你不应该在准备周数组时(在计算函数中)更改你的firstDay
属性。它会覆盖momentjs状态。在这种情况下,计算属性应该只读取firstDay
属性而不影响对它的更改。
同样在上一周和下周的操作中,您不必创建新的momentjs对象。例如,您可以轻松操作以前创建的firstDay
属性。
this.get('firstDay').subtract(7, 'days');
但在这种情况下,momentjs的状态已经改变,但是emberjs没有看到任何变化。这是因为你的firstDay
属性并没有真正改变(并且计算属性设置为仅检查firstDay
,它不能很好地工作)。实际上firstDay
属性只是对momentjs对象的引用,并且该对象已被更改,而不是引用。但幸运的是,您可以手动强制emberjs以这种方式基于任何属性重新加载任何计算属性:
this.notifyPropertyChange('firstDay');
如此重复的工作示例可能看起来像:
import Ember from 'ember';
export default Ember.Component.extend({
selectedWeek: moment().startOf('week'),
days: Ember.computed('selectedWeek', function() {
let printDay = this.get('selectedWeek').clone();
let week = [];
for (var i = 1; i <= 7; i++) {
week.push(printDay.format('MM-DD-YYYY'));
printDay.add(1, 'days');
}
return week;
}),
actions: {
currentWeek() {
this.set('selectedWeek', moment().startOf('week'));
},
previousWeek() {
this.get('selectedWeek').subtract(7, 'days');
this.notifyPropertyChange('selectedWeek');
},
nextWeek() {
this.get('selectedWeek').add(7, 'days');
this.notifyPropertyChange('selectedWeek');
}
}
});