我正在为我的应用程序构建一个简单的每周日历组件,而我正努力寻找一种创建周导航的方法。这是我到目前为止的内容:

/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>


目前,它仅在当前一周的前一周和之后的一周导航。非常感谢您对如何无限期地进行这项工作的任何想法。提前致谢。

最佳答案

我认为在对星期数组进行预配对时(在计算函数中),您不应更改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');
    }
  }
});

关于javascript - Ember.js每周日历导航,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41489636/

10-12 13:49