2

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 :)).

Lbro
  • 309
  • 2
  • 16

1 Answers1

4

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>

P.S.

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

Community
  • 1
  • 1
JayDi
  • 1,037
  • 15
  • 24
  • Thanks, to be frank I've seen this link [binding-behavior](https://www.danyow.net/aurelia-binding-behaviors/), but I didn't catch the thing :( Your example clarified it :) and now it works. – Lbro Oct 06 '16 at 12:10