简体   繁体   中英

Aurelia : Refresh view with a Map value

In the viewModel I have a Map which is refreshed every 5s :

 Constructor(){
        this myMap=new Map();

    }
    activate(){
       //for example :
       value=7;
       id=1;
       setInterval(()=>{
          this.myMap.set(id, value++);
          });
        },5000);
    }

In the view :

<template>
  <div class="container">
  <h2>${titre}</h2>
  <p class="nb-values-OK">
    ${myMap.get(1)}
  </p>
  </div>
</template>

Nothing happen when interval triggers ... Is there any way to have my view refreshed when the timer triggers ?

In fact in the real world, I have lanes and on these lanes there are some activities ; so my map do the link between a lane id and the number of activities which take place on that lane. It appears to me that a Map is the simplest way to sort this ... Anyway, my first question concerns the way to have my view refreshed every 5sec.

Thanks in advance for any help. `

(Hope my english is good enough to be understandable :)).

You need use bind(this) in callback-functions for access inner model data like this.myMap :

Constructor(){
    this myMap=new Map();
}

activate(){
    //for example :
    value=7;
    id=1;
    setInterval(function(){
        this.myMap.set(id, value++);
    }.bind(this), 5000);
}

If you need to observ and update complex data then you can use many bindable behaviors . Most simple solution -- using of signal api (view bindable value will be updated every time then you send special signal):

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

Also for custom property or expression observer you can use BindingEngine (create events on your map value change). See example in that topic: Property change subscription with Aurelia

Also you can try expressionObserver from BindingEngine (to observe array or "inner" object values): https://stackoverflow.com/a/33482172/1276632

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM