2014-09-03 27 views
0

我有一個<select>框定義一個「東西」,並設置model.thing和視圖正在觀察該模型的變化,然後做一些jQuery的噪音作出迴應。例如:

FooNewView = Ember.View.extend 

    selectedThing: (-> 
    @setNameIfUnset() 
).observes('controller.model.thing') 

    setNameIfUnset:() -> 
    console.log 'setNameIfUnset' 
    unless @$('#name-field').val().length 
     # set the name to the name of Thing if not set yet 

    didInsertElement:() -> 
    @_super() 
    Ember.Logger.info("FooNewView::didInsertElement") 

麻煩的是,觀察者似乎火一旦 didInsertElement被調用之前,因此this.$()在這一點上不確定的。

我的問題是:處理這個問題的最佳方法是什麼?我是否應該在didInsertElement中設置一個標誌並檢查setNameIfUnset?也許只是一個普通的老jQuery change聽衆添加到didInsertElement

回答

1

最好的方法是檢查在執行代碼observer之前是否定義了this.$(),而不是設置不必要的標誌和jQuery偵聽器。所以代碼將是

setNameIfUnset: function(){ 
    if(this.$()) { 
     console.log('setNameIfUnset'); 
     unless @$('#name-field').val().length 
     # set the name to the name of Thing if not set yet 
    } 
}