最有效的Aurelia绑定方式为单身对象 [英] Most efficient Aurelia binding way for a singleton object
问题描述
这是一个非常基本的JavaScript和Aurelia问题。
Here's a pretty fundamental JavaScript and Aurelia question.
假设我有一个单例对象,例如 User
它通常会从服务器获取更新,它返回一个全新的用户
对象。
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).
替换对象引用,并为所有侦听器推送 EventAggregator
通知,以重新查询用户
对象
Replace the object reference and push an EventAggregator
notification for all listeners to re-query the User
object.
我目前已经选择了1号选项,问题,但没有阻止。
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?
推荐答案
这是我的意见n。您不必使用 EventAggregator
,您也不必为更新每个资源而奋斗。您可以创建助手类( AppState
或某些东西)来保存您的用户
对象。在您的元素中,注入 AppState
类,并创建一个getter函数来返回 User
对象(使用 @computedFrom
或 aurelia-calculated
以避免脏检查)。例如:
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>
运行示例 https://gist.run/?id=f2ed9769343513b0819115863ff64c34
这篇关于最有效的Aurelia绑定方式为单身对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!