Skip to content

Instantly share code, notes, and snippets.

@treinberger
Created October 26, 2012 07:11
Show Gist options
  • Save treinberger/3957353 to your computer and use it in GitHub Desktop.
Save treinberger/3957353 to your computer and use it in GitHub Desktop.
Alloy view databinding sample
function MapModelToView(model, view) {
var databoundViews = getChildren(view).filter(function(subview) {
return !_.isUndefined(subview.dataField);
});
for (var prop in model) {
if (model[prop] != null && !_.isFunction(model[prop]) && !_.isArray(model[prop])) {
//try to find view with attribute dataField = prop
var matchingSubview = _.find(databoundViews, function(subview) {
return subview.dataField === prop;
});
if (matchingSubview != null) {
Ti.API.debug("View->Model model." + prop + "=" + model[prop]);
matchingSubview.value = model[prop];
}
}
}
}
function MapViewToModel(view) {
var model = {};
//get all views with databinding and add their respective property values to the configuration object
//currently works only for flat objects
_.chain(getChildren(view)).filter(function(subview) {
return !_.isUndefined(subview.dataField);
}).each(function(subview) {
viewHasBindings = true;
var fieldValue = getViewValueFromMapper(subview);
model[subview.dataField] = fieldValue;
Ti.API.debug("Model->View view." + subview.dataField + "=" + fieldValue);
});
return model;
}
function getChildren(view) {
//Ti.API.debug("processing view " + view.id);
var result = [];
var thisChildren = view.getChildren();
result = result.concat(thisChildren);
_.each(thisChildren, function(v) {
result = result.concat(getChildren(v));
});
return result;
}
var __sampleModel = {attr1: "value1", attr2: "value2"};
//sample usage:
//loading data into view:
MapModelToView(__sampleModel, $.rootContainer);
//writing view state back into the model:
_.extend(__sampleModel, MapViewToModel($.rootContainer));
<Alloy>
<Window id="rootContainer" title="New">
<ScrollView layout="vertical">
<View>
<Label text="Active"/>
<Switch id="swActive" value="true" dataField="active"/>
</View>
<Label text="Description" top="20"/>
<TextArea id="taDescription" styleClass="textfield" hintText="test" dataField="description"></TextArea>
<Label text="Subject (E-Mail only)"/>
<TextArea id="taSubject" dataField="subject"></TextArea>
<Label text="Text"/>
<TextArea id="taSmsText" dataField="body"></TextArea>
<View>
<Label text="Send SMS"/>
<Switch id="swSendSms" value="true" dataField="sendSMS" onChange="handleMethodSwitchChange" actionTargetViewID="btnEditSmsRecipients"/>
</View>
<Button id="btnEditSmsRecipients" title="Edit SMS Recipients" onClick="editRecipients" type="sms" nextID="v1"/>
</ScrollView>
</Window>
</Alloy>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment