2014-07-18 32 views
0

我的路由器看起來像這樣。EmberJS - 保持模型與localStorage中的數據同步

-Contacts 
    -Details 
-Dashboard 
-Listings 

一旦觸點打開(即,過渡到contacts.details),即接觸應recent contacts下進行跟蹤。這些recent contacts然後顯示在其他路線,如dasboardlistings。我在ContactsDetailsController的內部添加了一個名爲updateRecentContacts的操作。在這裏,我手動將這些聯繫人保存到本地存儲。

APP.ContactsDetailsController = Ember.ObjectController.extend({ 
    actions: {  
     updateRecentContacts: function(contact) { 
      // Do some processing and then add it to localStorage 
      // Note: store refers to a localStorage plugin. Not Ember Data 
      store.set('recentContacts', recentContacts); 
     } 
    } 
}); 

因爲這些contacts將被顯示在各個航線上,我在ApplicationController增加了一個名爲recentContacts屬性和設置它的值從localStorage數據。現在,我可以使用render幫助程序在任何路線中呈現這些聯繫人,並提供此ApplicationController的contacts屬性作爲模型。

App.ApplicationController = Ember.ArrayController.extend({ 
     recent: { 
      contacts: store.get('recentContacts') 
     } 
    }); 


<script type="text/x-handlebars" data-template-name="recentContacts"> 
    {{#each contact in controllers.application.recent.contacts}} 
     <!-- Render this template using {{render}} helper in any other view --> 
    {{/each}} 
</script> 

這工作,但所呈現的數據是從localStorage的數據外的日期。硬刷新後纔會顯示正確的數據。

我的問題是,我如何保持這些數據同步?我甚至不確定我是否以正確的方式做這件事。當然,其他人一定會遇到一種情況,他們需要更有效地跟蹤路線上的事情(最近的帖子,文章等)。我沒有使用Ember Data,因爲我不確定它是否值得用於這個recentContacts模型。

回答

0

您需要手動更新ApplicationController的屬性值以反映您的更改。

在你的情況下,我會這樣做,假設你不想改變你的details(在我的案例index)控制器內的任何東西。

通過needs屬性注入您的應用程序控制器。基本上計算的別名是可選的,但是我們喜歡幻想和光澤,我們不..

App.IndexController = Ember.Controller.extend({ 
    needs: 'application', 
    application: Ember.computed.alias('controllers.application') 
}); 

的ApplicationController中可能看起來像:

App.ApplicationController = Ember.Controller.extend({ 
    recent: { 
    contacts: ['red', 'yellow', 'blue'] 
    } 
}); 

重要一部分位於ApplicationRoute。在這裏我們處理由於餘燼事件冒泡而來的行動。在這裏,我們可以更改應用程序控制器屬性,如果數據綁定正確,它將反映在整個應用程序中。

App.ApplicationRoute = Ember.Route.extend({ 
    actions: { 
    updateContacts: function() { 
     console.log('Doing stuff in application route...') 
     this.controller.recent.contacts.pushObject('gold'); 
    } 
    } 
}) 

模板看起來像

<script type="text/x-handlebars" data-template-name="index"> 
    <ul> 
    {{#each application.recent.contacts }} 
    <li {{action 'updateContacts'}}>{{this}}</li> 
    {{/each}} 
    </ul> 
</script> 

要看到它在行動這裏是你jsbin:您的時間http://emberjs.jsbin.com/dibep/1/edit

+0

您好奧利弗,謝謝。這很好。因爲我們在'details'中引用'ApplicationController',我們不能直接在那裏更新'recent.contacts'屬性嗎?我嘗試了它,它似乎按預期工作,但不知道它是否正確。 – Sparda

+0

我相信這兩種方式都有正反兩面。事件鼓勵更鬆散耦合的設計,而方法調用確保冒泡路徑上沒有其他實例「意外」消耗事件。 – Oliver

相關問題