EmberJS 2.3.0可重复使用的功能

时间:2016-02-04 04:50:43

标签: ember.js

我定义了一个组件,它将成为我所有网页的侧边栏。在这个组件中,有一个我想写的部分显示了接下来的三个会议日期。为了生成这些日期,我编写了一些自定义javascript函数,创建了日期数组,然后将其附加到模型中。这是在索引路由文件中完成的。从那里我可以将该数组传递给组件

{{main-sidebar model=model.meetingDates}}

所以在我的索引路径中,这就是我构建它的方式,它工作得很好。

export default Ember.Route.extend({
  model() {
    var getThirdWed = function(customDate, currentDate, wedCount) {
      // Keep uping the date of the month till we hit a wed
      while (customDate.getDay() !== 3) {
        customDate.setDate(customDate.getDate() + 1);
      }

      // Set date based of wedCount
      customDate.setDate(customDate.getDate() + (7 * (wedCount - 1)));

      if (customDate.getTime() > currentDate) {
        var month = customDate.toLocaleString("en-us", {
          month: "long"
        });
        var ordinal = "th";

        if (customDate.getDate() < 3) {
          ordinal = "st";
        }

        if (customDate.getDate() > 20) {
          ordinal = "st";
        }

        return month + " " + customDate.getDate() + "" + ordinal + " at 7:15pm";
      }

      return "";
    };

    var getNextMeeting = function(meetingCount, wedCount) {
      var now = new Date();
      var currentDate = now.getTime();
      var customDate = now;

      // Set the date to the first of the month
      customDate.setDate(1);

      // If meetingCount is 0 that means we want the current month
      if (meetingCount === 0) {
        return getThirdWed(customDate, currentDate, wedCount);
      } else {
        // Set to a future month
        customDate.setMonth(customDate.getMonth() + meetingCount);

        return getThirdWed(customDate, currentDate, wedCount);
      }

      return "";
    };

    var meetingDates = [];
    var count = 0;

    while (count < 3) {
      var date = getNextMeeting(count, 3);

      if(date !== '') {
        meetingDates.push(date);
        count++;
      }
    }

    model.meetingDates = meetingDates;

    return model;
  },
});

接下来我生成一个名为cost的新路由。那么我是否必须复制所有代码以再次生成日期数组,或者是否有更好的地方放置这些JS函数以便我可以在所有页面上重用它们?

0 个答案:

没有答案