Aurelia:修改任何 属性 时的通知

Aurelia: notification when ANY property is modified

您是否有任何方法可以知道何时通过绑定修改了任何模型的 属性? 我需要一些通用的东西,因为它将应用于所有形式的应用程序。这意味着我不能只为模型的每个属性设置一个 '属性'Changed() 可观察回调。我正在考虑覆盖绑定引擎创建的属性设置器的方法,以便它们可以调用单个定义的回调,但我觉得可能有更好的方法。

我为这种情况(以及更多)创建了一个 aurelia 插件。 这不完全是您的要求,但可以为您提供很多帮助。 因为该插件将创建一个名为 isDirty 的 属性,您可以观察并相应地触发您的代码。

https://github.com/avrahamcool/aleph1-aurelia-utilities

查看Dirty Tracking a model:部分

your model class need to extends the baseClass provided by the plugin. now you can decorate any properties of your model with the @dirtyTrack() decorator.

for babel users: the assignment in the declaration will set the default value for the property. for TS users: you should call the decorator with a parameter @dirtyTrack(7) someInt: number;

this will set up a isDirty variable in your model. this property will be automatically updated to with every change to your tracked properties.

at any point, you can call saveChanges() on your model, to commit the current changes. or discardChanges() to revert back to the last saved point. you can call serialize() to get a pojo object from your model, or deserialize(pojo) to populate your model from a pojo object.

好的,我最后只是使用绑定引擎来观察所有属性的变化。这使我能够在不修改现有模型的情况下实施我的 isDirty 检查...

因此最终代码如下所示:

Object.getOwnPropertyNames(obj).forEach(p => {
        this.subscriptions.push(this.binding.propertyObserver(obj, p)
           .subscribe(() => this.updateDirty()));
    });

我的 updateDirty() 方法在每次 属性 更改后调用,并且模型不需要更改。

如果有人能想出更好的解决方案,我仍然很感兴趣,但这暂时符合我的需求。