I'm trying to move toward using the View/Model/View-Model or Presentation Model pattern in a Flex application since it definitely feels like the "correct" way to do things. I have a question about how something should work with Flex data binding though.
Say I have a Project
model class which contains a bindable name field. I want to make a report to display information about the project. The title of the report should be [Project Name] Summary. I want to make a View-Model class to provide the backing for the report. This SummaryViewModel
class will have a title
field to provide the report title.
In my report mxml I would bind the title label to summaryModel.title
, however title
needs to somehow be bound to projectModel.name
so if the name is changed in another part of the program the report title updates also.
What's the correct way to accomplish this "two-level" data binding in Flex? Should I be doing things a different way?
Let's say you have a model like this:
[Bindable]
public class Project {
public var name:String;
}
And you have your presentation model:
[Bindable]
public class SummaryPresentationModel
{
private var projectModel:Project = new Project();
public var title:String;
}
In your constructor, you can data bind the setter of the model to a function that sets the title:
public function SummaryPresentationModel() {
BindingUtils.bindSetter(modelNameChanged, projectModel, "name");
}
And then set the value of title
:
private function modelNameChanged(newValue:String):void {
title = "[" + projectModel.name + "] Summary";
}
You are then free to bind to the summaryPM.title
and everything will chain to the UI when projectModel.name
changes.
You can get more complicated and use a "getter" function on title
(as opposed to just setting it like I am here), but you need to propagate the change notification. I is not too terribly difficult to do, but I find that this method is a bit easier to follow.
Hope this helps!