2013-08-06 71 views
0

我已經在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

感謝您的任何建議!

回答

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上的選項和事件處理程序聲明爲普通屬性。泛型類負責將所有這些東西傳遞給底層的日期選擇器對象。

這種方法受repo of Luke Melia的啓發,它再次受到湯姆戴爾的代碼啓發& EmberJS的兩個創造者Yehuda Katz。

相關問題