2013-05-02 71 views
-1

我正在嘗試執行路由器事件並使用路由器的發送功能來觸發路由器上的事件。但無法獲得任何文件。
我想實現的是我從控制器/視圖引發事件從服務器獲取數據。事件異步地從服務器獲取數據,並且當數據成功獲取時,我想從我稱之爲事件的位置初始化視圖的子視圖,即我需要知道數據何時被獲取。但我不認爲路由器上的事件會返回任何可以讓我知道呼叫何時結束的事件。
喜歡的東西:
查看:Em.Route#發送一些幫助?

Em.View.extend({ 
    click: function(){ 
     var recordsPromise = this.get('controller.target').send('getRecords'); 
     recordsPromise.done(this.initiateProtocol); 
    }, 

    showChild: false, 
    initiateProtocol: function(){ 
     //this showChild is used as a condition in the template to show/hide 
     // the childview. And is being set after the call completed 
     // successfully 
     //here childOneView is present some other js file and is fetched using requirejs 
     require(['childOneView'], $.proxy(function(childOneView){ 
      this.set('childOne', childOneView.extend({ 
       templateName: 'childOne' 
      }); 
      this.set('showChild', true); 
     }, this)); 

    } 
} 

路由器

Em.Route.extend({ 
    events: { 
     getRecords: function(){ 
      //make an ajax call to fetch the records and return the ajax as a 
      // promise 
     } 
    } 
}); 

模板

​​
+0

您使用的餘燼數據? – intuitivepixel 2013-05-02 15:09:20

+0

@intuitivepixel不,我沒有使用燼數據。只需一個簡單的ajax調用服務即可。 – guleria 2013-05-02 15:11:25

+0

你打算使用什麼框架來實現「承諾」?着名的discourse.org應用程序是用燼而不是燼數據使用這一個https://github.com/tildeio/rsvp.js – intuitivepixel 2013-05-02 15:16:52

回答

0

我覺得idiomat ic Ember方法會有點不同。向上送出動作控制器,讓它泡到航線,然後設置屬性,你的觀點將通過綁定迴應:

查看

App.RecordsView = Em.View.extend(Ember.ViewTargetActionSupport, { 
    click: function(){ 
    this.triggerAction({action: 'getRecords'}) 
    } 
}); 

控制器

App.RecordsController = Em.ArrayController.extend({ 
    content: [], 
    isLoaded: false 
}); 

模板

<!-- records.handlebars --> 
{{#if isLoaded}} 
    render stuff here... perhaps {{#each this}}{{someRecordProperty}}{{/each}} 
{{/if}} 

路由器

App.RecordsRoute = Em.Route.extend({ 
    events: { 
    getRecords: function(){ 
     var controller = this.controllerFor('records'); 
     $.ajax(...).then(function(data){ 
     Em.run(function(){ 
      controller.setProperties({ 
      content: data.foo, 
      isLoaded: true 
      }); 
     }); 
     }); 
    } 
    } 
}); 
+0

這種方法已經足夠,但我真正的問題是不知道何時呈現我的觀點。我正在使用requirejs,並且想要在從服務器成功獲取數據時獲取我的子視圖。並將其設置在調用成功時將調用的函數中,即我想在需要時獲取資源。我已更新我的問題以更好地顯示我的要求。 – guleria 2013-05-03 17:22:17

+0

我找到了一條出路。我們可以使用回調函數,並在獲取記錄後從路由事件中調用方法來運行。在成功完成可以在模板中訪問的呼叫後,數據將被設置到控制器。我在這裏有一個示例小提琴這個方法:http://jsbin.com/ajuwis/4/edit。但是,如果這是正確的方式,或者是否有更好的方法呢? – guleria 2013-05-03 18:59:09

+0

IMO,如果您從視圖發送到控制器/路由器的操作是「沒有附加任何字符串」,您將最終得到一個更清潔的體系結構。沒有回調,沒有承諾,沒有返回值。取而代之的是讓你的視圖綁定或觀察你從路由器設置的控制器屬性/事件。 – 2013-05-03 21:05:27