As I was not finding an appropriate MVC solution for a Titanium mobile project, I came up with the following approach. For small apps this might be over-engineered but could help for maintaining growing applications.
Folder structure:
/Resources
/model
/view
/controller
/ui
/iphone
/android
app.js
app.jss
For separating views, models and controllers a namespace is needed, so we define it in the app.js, which is our main controller:
var app = {
view: {},
controller: {},
model: {},
ui: {}
}
Within the folders we place single JavaScript files for each component. For this we could either use a lightweight JavaScript OOP library, such as MooTools or Prototype or define simple JS functions as our objects. If you also want to inherit from parent classes, a library definitely makes sense.
Examples:
# Resources/controller/MyController.js
app.controller.MyController = function() {
return {
getView: function() {
return new app.view.MyView().getView();
}
}
}
# Resources/view/MyView.js
app.view.MyView = function() {
return {
getView: function() {
return Ti.UI.createWindow({...});
}
}
}
# Resources/view/MyModel.js
app.model.MyModel = function() {
return {
some: "data",
foo: "bar"
}
}
After that we can include all needed model/view/controller classes with Ti.include() in the app.js file and reference the components with our namespace:
Ti.include("controller/MyController.js");
Ti.include("view/MyView.js");
var myController = new app.controller.MyController();
var myView = myController.getView();
myView.open();
The MVC approach would now presume that the controller "controls" the state of the view and passes data from the model into the view. The view consists only of UI elements and properties for styling. Any action which is made in the UI fires an event, which tells the controller to perform the desired action.
But of course, the exact definition of MVC might be different according to your personal taste ;)