开发者

Options for keeping models and the UI in sync (in a desktop application context)

开发者 https://www.devze.com 2022-12-23 03:11 出处:网络
In my experience I have only had 2 patterns work for large-scale desktop application development when trying to keep the model and UI in sync.

In my experience I have only had 2 patterns work for large-scale desktop application development when trying to keep the model and UI in sync.

1-An eventbus approach via a shared eventbus command objects are fired (ie:UserDemographicsUpdatedEvent) and have various parts of the UI update if they are bound to the same user object updated in this event.

2-Attempt to bind the UI directly to the model adding listeners to the model itself as needed. I find this approach rather clunky as it pollutes the domain model.

Does anybody have other suggestions? In a web application with something like JSP binding to the model is easy as you ussually onl开发者_如何学运维y care about the state of the model at the time your request comes in, not so in a desktop type application.

Any ideas?


I am currently using the event bus approach to synchronize the models and the UI in my application, but I have hit a hurdle with it in that it's difficult to make it very fine grained, for example, at the property level where you are just interested in knowing if property x of an object gets updated, and there are hundreds or thousands of such cases.

For such a fine grained control, you might want to checkout how KVC (Key Value Coding) and KVO (Key Value observing) works in Cocoa. It basically allows an object to observe any other object's properties as long as it uses some basic principles of KVC. The interested objects automatically get notified upon changes, and you don't have to explicitly notify the observing objects on each property change as that is taken care of by the underlying implementation of KVO. It is somewhat similar to the PropertyChange listeners in Java beans.

If there is too many observations going on, and writing the glue code to update models/views on property changes becomes problematic, you might want to take it a step further and have data-binding to keep models and views synchronized. Built upon the concepts of KVO, the idea is to bind properties of objects, so that a change in one automatically updates the other, and vice versa. For example, you could bind the text in SO's answer field, to the answer preview that we see right below.

.bind('answer.value', 'answerPreview.text')

Both happen to be view elements in this case, so data-binding is a generic approach, and can be used to bind objects more appropriately and not just UI with models.

0

精彩评论

暂无评论...
验证码 换一张
取 消