[英]Polymer - JavaScript - Data Binding: Real-time update?
我有兩個頁面: my-view1
和my-view2
。 在my-view1上,我有兩個按鈕可以在LocalStorage中添加和刪除數據。 在my-view2上,我有兩個簡單的div,分別讀取(顯示)總價值和最近6個月的總價值。
但是,在第二頁上,如果不刷新頁面,則該值不會更新。 我希望my-view2中的值在每次頁面加載(查看,即使已緩存)時自動更新。
這是帶有my-view2的plnkr,因此您可以放棄我正在嘗試做的事情。
https://plnkr.co/edit/ul4T2mduxjElCN4rUUKd?p=info
我怎樣才能做到這一點?
您可以在更新localStorage時監聽storage
事件以觸發並更新my-view2中的一些道具:
<my-view-2 id="myView2"></my-view-2>
<script>
window.onstorage = function(e) {
if (e.key !== 'someKeyYouWant') return;
document.getElementById('myView2').set('someProp', {
oldValue: e.oldValue,
newValue: e.newValue
});
};
</script>
編輯( 工作 ):由於此處描述的行為,存儲事件將不會在發起更改的窗口上觸發,因此您必須觸發自己的存儲事件,請考慮以下方法:
saveToLs(e) {
e.preventDefault();
const newName = this.get('dogName');
const ls = window.localStorage;
const synthEvent = new StorageEvent('storage');
const eventConfig = [
'storage',
true,
true,
'myDog',
ls.getItem('myDog'),
newName
];
synthEvent.initStorageEvent(...eventConfig);
setTimeout((() => { // ensure async queue
ls.setItem('myDog', newName);
this.dispatchEvent(synthEvent);
}).bind(this), 0);
}
...在聆聽方面:
handleStorageUpdate(e) {
if (e.key !== 'myDog' || e.newValue === this.get('dogName')) return;
this.set('dogName', e.newValue);
}
請注意if
有條件處理可能重復更新的值相同。
這是一個工作的小伙伴 ,您可以玩
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.