Aurelia: notification when ANY property is modified

為{幸葍}努か 提交于 2019-12-08 02:07:37

问题


Do you see any way to know when ANY model’s property has been modified through a binding? I would need something generic because it would be applied to all the forms of the application. This means I cannot just have a 'property’Changed() observable callback for every properties of the models. I’m thinking along the ways of overriding the properties setters created by the binding engine so they can call a single defined callback but I feel like there could be a better way.


回答1:


I created a aurelia-plugin for this kind of scenario (and more). Its not exactly what your asking for, but can help you a lot. because the plugin will create a single property called isDirty that you can observe and fire your code accordingly.

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

look at the Dirty Tracking a model: section

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.




回答2:


Ok, I ended up just using the binding engine to watch all properties changes. This allowed me to implement my isDirty checks without modifying the existing models...

So the final code looks like this:

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

my updateDirty() method is called after every property change and no change was necessary to the model.

If anyone can come up with a better solution, I'm still interested but this fits my needs for the time being.



来源:https://stackoverflow.com/questions/53212581/aurelia-notification-when-any-property-is-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!