2015-01-08 68 views
0

我有一個組件,它爲<select>標籤添加了一些功能。我想在<select>完全呈現之後初始化一些javascript,包括所有<option>標記。用於填充<option>標記的數據是從ajax請求提供的對象數組。Ember在解決諾言之前選擇組件渲染

我使用的是ember-data,當數據是從商店提供的,這意味着它是DS.RecordArray的一個實例,它具有有用的屬性,如isLoaded。但是,當數據是從jQuery ajax調用提供的,並且只是普通的JSON時,它看起來好像組件試圖在jQuery返回的promise實現之前呈現所有內容。

我覺得問題在於我如何處理承諾,因爲問題似乎與事先初始化之前的事情有關(即承諾已妥善解決)。我嘗試在RSVP.Promise對象中包裝ajax調用,但不是運氣,(我正在使用Ember-CLI)。以下是我迄今爲止的簡化版本。任何幫助,將不勝感激。

// My route 
export default Ember.Route.extend({ 
    setupController: function(controller, model) { 
     this._super(controller, model); 

     var hash = Ember.RSVP.hash({ 
       // myOptions: $.getJSON('/api/options') 
       myOptions: new Ember.RSVP.Promise(function(resolve, reject) { 
        Ember.$.ajax({ 
         url: '/api/options', 
         type: 'get', 
         dataType: 'json', 
         success: function(result) { 
          Ember.run(null, resolve, result); 
         }, 
         error: function(result) { 
          Ember.run(null, reject, result); 
         } 
        }); 
       }) 
      }); 

     return hash.then(function(result) { 
      controller.set('optionsForSelect', result.myOptions); 
     }); 
    } 
}); 

// My component 
export default Ember.Select.extend({ 
    didInsertElement: function() { 
     // Is called before ajax request has finished 
     this.$().mySelectPlugin({ 
     }); 
    } 
}); 

// Handlebars template 
{{my-select-plugin content=optionsForSelect optionValuPath="content.id" optionLabelPath="content.name"}} 
+1

從'setupController'返回一個承諾不會做任何有用的事情。嘗試從'model'(或'beforeModel'或'afterModel')返回承諾。 –

+0

是的,你是對的@torazaburo。謝謝你的幫助。 – antony

回答

2

對我來說,這似乎是應該在控制器中處理的東西,而不是路由。這是我爲類似的情況所做的。

App.LessonsShowIndexController = Ember.ObjectController.extend({ 
    author: function() { 
     return this.get('model').get('author'); 
    }.property('author'), 
    fullName: function() { 
     return this.get('author').get('firstName') + ' ' + this.get('author').get('lastName'); 
    }.property('author.isFulfilled'), 
}); 

使用isFulfilled屬性允許控制器在使用數據之前等待解決承諾。在你的情況下,你可以有一個屬性返回一個承諾,另一個等待它履行。

+0

不錯!這種方法也適用於組件 –

相關問題