[英]Aurelia : Refresh view with a Map value
在viewModel中,我有一個Map,每5s刷新一次:
Constructor(){
this myMap=new Map();
}
activate(){
//for example :
value=7;
id=1;
setInterval(()=>{
this.myMap.set(id, value++);
});
},5000);
}
在視圖中:
<template>
<div class="container">
<h2>${titre}</h2>
<p class="nb-values-OK">
${myMap.get(1)}
</p>
</div>
</template>
間隔觸發時什么也沒有發生...定時器觸發時有什么方法可以刷新我的視圖?
實際上,在現實世界中,我有車道,在這些車道上有一些活動。 因此我的地圖將車道ID與該車道上發生的活動數量聯系起來。 在我看來,映射是最簡單的排序方式……無論如何,我的第一個問題是關於每5秒刷新一次視圖的方式。
在此先感謝您的幫助。 `
(希望我的英語足夠好,可以理解:)。
您需要在回調函數中使用bind(this)
來訪問內部模型數據,例如this.myMap
:
Constructor(){
this myMap=new Map();
}
activate(){
//for example :
value=7;
id=1;
setInterval(function(){
this.myMap.set(id, value++);
}.bind(this), 5000);
}
如果需要觀察和更新復雜數據,則可以使用許多可綁定的行為 。 最簡單的解決方案-使用signal api(每次發送特殊信號后,視圖可綁定值都會更新):
model.js :
import {inject} from 'aurelia-dependency-injection';
import {BindingSignaler} from 'aurelia-templating-resources';
@inject(BindingSignaler)
export class SampleView {
constructor(signaler) {
this.signaler = signaler;
}
activate() {
this.data = new Map();
this.data.set(1, 1);
// data changing by interval and send update signal
setInterval(function(){
this.data.set(1, this.data.get(1) + 1);
this.signaler.signal('need-update');
}.bind(this), 1000);
}
}
model.html
<template>
<h1>${data.get(1) & signal:'need-update'}</h1>
</template>
PS
同樣對於自定義屬性或表達式觀察器,您可以使用BindingEngine(在地圖值更改時創建事件)。 請參閱該主題中的示例: 使用Aurelia進行屬性更改訂閱
您也可以嘗試從BindingEngine的expressionObserver(觀察數組或“內部”對象值): https : //stackoverflow.com/a/33482172/1276632
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.