我的路由器看起來像這樣。EmberJS - 保持模型與localStorage中的數據同步
-Contacts
-Details
-Dashboard
-Listings
一旦觸點打開(即,過渡到contacts.details
),即接觸應recent contacts
下進行跟蹤。這些recent contacts
然後顯示在其他路線,如dasboard
和listings
。我在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
模型。
您好奧利弗,謝謝。這很好。因爲我們在'details'中引用'ApplicationController',我們不能直接在那裏更新'recent.contacts'屬性嗎?我嘗試了它,它似乎按預期工作,但不知道它是否正確。 – Sparda
我相信這兩種方式都有正反兩面。事件鼓勵更鬆散耦合的設計,而方法調用確保冒泡路徑上沒有其他實例「意外」消耗事件。 – Oliver