问题
Here's a pretty fundamental JavaScript and Aurelia question.
Let's say that I have a singleton object, for example User
and it would often get updates from the server, which returns a whole new User
object.
Now, to push the update to the views, I have two options (that I know of):
Update every property of the existing
User
to that of the newUser
's manually (this would also require mapping every property).Replace the object reference and push an
EventAggregator
notification for all listeners to re-query theUser
object.
I have currently gone for option number 1, which has raised some issues, but nothing blocking.
Which one would be more efficient and/or provide more benefits over the other?
回答1:
Here's my opinion. You don't have to use EventAggregator
, and you also don't have to struggle updating every property. You could create helper class (AppState
or something) to hold your User
object. In your elements, inject the AppState
class and create a getter function to return the User
object (use @computedFrom
or aurelia-computed
to avoid dirty-checking). For example:
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>
Running example https://gist.run/?id=f2ed9769343513b0819115863ff64c34
来源:https://stackoverflow.com/questions/40263660/most-efficient-aurelia-binding-way-for-a-singleton-object