在 Flex 中,我如何知道动态对象的属性何时发生变化?
我有一个动态类,用作配置设置的存储容器。 设置是该类的变量,它具有读取和写入配置文件、数据库等的方法。现在我想在类变量发生更改时触发写入持久存储。 由于变量是在运行时动态添加的,因此我无法使用 get/set 方法,而且,如果可以的话,这将导致大量的样板代码。
如何触发事件来更改我的类的属性?
I have a dynamic class that serves as a storage container for configuration settings. The settings are variables of that class and it has methods to read from and write to a configuration file, database etc. Now I want to trigger writing to the persistant storage whenever a class variable is changed. As the variables are added dynamically at runtime, I can't use get/set methods, also, if I could, that would lead to a lot of boilerplate code.
How can I have an event triggered for changing properties of my class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从
mx.utils 继承此类.代理
。 它允许您使对象是动态的,但仍然能够编写一些在访问属性时运行的自定义代码(类似于 getter 和 setter - 请参阅getProperty()
和setProperty()
。)You can subclass this class of yours from
mx.utils.Proxy
. It allows you to have the object be dynamic yet still be able to write some custom code that runs whenever properties are accessed (similarly to getters and setters -- seegetProperty()
andsetProperty()
.)我会考虑避免使用动态对象,而是使用一种存储方法和一种检索数据的方法创建数据存储类(SettingsModel?)。 因此,不要使用:
...您可以编写:
您可以将命名设置存储在字典内部,并在
store()
方法中执行任何需要完成的操作。这里的主要优点是可读性:当您看到一个方法被调用时,您就知道它背后有功能。 出于同样的原因,我倾向于不喜欢 getter/setter 函数。
最后,这是一个品味问题,所以如果你的代码没有被破坏,为什么要修复它呢。 :)
I would consider avoiding the dynamic object, and rather create the data storage class (SettingsModel?) with one method for storing and one method for retrieving data. So instead of using:
...you would write:
You could store the named settings internally in a Dictionary, and do whatever magic needs to be done in the
store()
method.The main advantage here is readability: when you see a method being called, you know there's functionality behind it. For the same reason I tend to dislike getter/setter functions.
In the end it is a matter of taste, so if your code isn't broken, why fix it. :)