The Most Effective Aurelia Binding Method for a Singleton Object

Here is a pretty important JavaScript and Aurelia question.

Say I have a singleton object, for example User, and it often receives updates from a server that returns a whole new object User.

Now, to click update on the views, I have two options (what I know):

  • Manually update each property of an existing one Userto a new one User(this also requires matching each property).

  • Replace the object reference and click the notification EventAggregatorfor all listeners to re-request the object User.

Currently, I have switched to option number 1, which raised some problems, but does not block anything.

Which of them will be more effective and / or will give more advantages in comparison with others?

+4
source share
1 answer

Here is my opinion. You do not need to use EventAggregator, and you also do not need to struggle with updating each property. You can create a helper class ( AppStateor something else) to hold the object User. In your elements, enter a class AppStateand create a getter function to return the object User(use @computedFromor aurelia-computedto avoid dirty checking). For instance:

Js

import { AppState, MyClass } from './app-state';
import { computedFrom } from 'aurelia-framework';

export class MyElement {

  static inject = [AppState];

  constructor(appState) {
    this.appState = appState;

  }

  @computedFrom('appState.obj')
  get obj() {
    return this.appState.obj;
  }

  updateObject() {
    this.appState.obj = new MyClass(); 
  }
}

HTML

<template>
  <h1>Element 1</h1>
  <button click.delegate="updateObject()">Update Object</button>
  <br><br>
  ${obj.p1} 
  <br><br><br>
  ${obj.p2}
</template>

Execution example https://gist.run/?id=f2ed9769343513b0819115863ff64c34

+2
source

Source: https://habr.com/ru/post/1658939/


All Articles