是否有更简洁的方法来设置它?

时间:2013-08-06 05:43:12

标签: ember.js datepicker

我在Ember视图中包含了一个bootstrap-datepicker,但我对结果不太满意。有更清洁的方法吗?

App.DatepickerView = Ember.View.extend({

  classNames: ['dp'],

  didInsertElement: function() {
    var _this = this;

    this.$().datepicker({'format': 'M yyyy','minViewMode': 'months'})
      .on('changeDate', function(e) {
        var id = $(this).datepicker().data('date').replace(" ", "-");

        _this.get('controller').transitionToRoute('month', App.Month.find(id));
      });

    this.$('.month.active').removeClass('active');

    if (this.get('controller.controllers.month.content')) {
      this.update();
    }

  },

  update: function() {
    var month = moment( this.get('controller.controllers.month.id') );
    this.$().datepicker('hide');
    this.$().datepicker('setDate', month.toDate());
    this.$().datepicker('show');
  }.observes('controller.controllers.month.content')

});

特别是我想

  • 在我的模板中或通过changeDate处理程序
  • 更惯用地处理click事件
  • 解决日期更新,如果我们通过数据绑定开始一个月(目前我检查是否设置了controllers.month.content,并更新didInsertElement上的日期选择器

感谢您的任何建议!

1 个答案:

答案 0 :(得分:2)

我对bootstrap-datepicker一无所知,但我相信你必须写一个像这样的基本集成并将你的Datepicker基于它。我使用jQuery UI而不是Bootstrap做了类似的事情。

// generic logic so that options and event handlers can be declared nicely
App.GenericDatePickerView = Ember.View.extend({
  didInsertElement: function() {
    var options = this._gatherOptions();

    var datepicker = this.$().datepicker(options);
    this.get("uiEvents").forEach(function(uiEvent){
      datePicker.on(uiEvent, function(){
        var fn = that.get(uiEvent);
        fn.call(that);
      });
    });
    this.set("datepicker", datepicker);
  },
  _gatherOptions: function() {
    var uiOptions = this.get('uiOptions'), options = {};
    uiOptions.forEach(function(key) {
      options[key] = this.get(key);
    }, this);

    return options;
  }
});

App.YourDatePicker = App.GenericDatePickerView.extend({
    uiOptions : ["format", "minViewMode"],
    uiEvents : ["onChange"],

    format : "M yyyy",
    minViewMode : "months",
    onChange : function(){
        var id = this.get("datepicker").data('date').replace(" ", "-");
        this.get('controller').transitionToRoute('month', App.Month.find(id));
    }
});

注意:我没有测试过此代码,但这是基本方法。您将DatePicker上的选项和事件处理程序声明为普通属性。 Generic Class负责将所有这些东西传递给底层的datepicker对象。

这种方法受到repo of Luke Melia的启发,再次受到Tom Dale& Yehuda Katz,EmberJS的两位创作者。