In part 2 we learned how to improve a standard distribution of Appcelerator on Rails. Now we will see it in action.
We are going to create a small application with 2 empty tab, with a very simple logic, that at the end will look like this.
First create the controllers and the views. We need the ruby
interpreter (version 1.8.7) in ordert to run the generators. If you have no Ruby interpreter installed on your system, you can find one here.
First controller:
ruby scripts/generate.rb controller Products Resources/controllers/products.js Resources/views/products.js
Generated code:
Resources/controllers/products.js
Ti.include("/views/products.js"); var ProductController = Controller.extend({ init: function(win) { this._super(win); this.view = new ProductView(win, this); } });
Resources/views/products.js
var ProductView = View.extend({ init: function(win, controller) { this._super(win, controller); this.layout(); }, layout: function() { } });
Second controller:
ruby scripts/generate.rb controller Clients Resources/controllers/clients.js Resources/views/clients.js
Now add some (simple) logic to the first controller:
btnClicked: function(event) { alert("click"); }
and write code that builds the interface using th controller logic:
layout: function() { this.win.title = 'Products'; this.win.backgroundColor = '#fff'; var label = Titanium.UI.createLabel({ color:'#999', text:'I am Products Window', font:{fontSize:20,fontFamily:'Helvetica Neue'}, textAlign:'center', width:'auto', }); this.win.add(label); var button = Titanium.UI.createButton({ title:'Click me', font:{fontSize:12,fontWeight:'bold'}, width:65, height:30, top:300 }); button.addEventListener('click', this.controller.btnClicked); this.win.add(button); }
You can made the same operation on the other controller and view.
In the app.js
file we only setup properties, create tabs and instantiate controllers. Nothing more.
Titanium.UI.setBackgroundColor('#000'); var tabGroup = Titanium.UI.createTabGroup(); // Product tab (root tab) var productWin = Ti.UI.createWindow({exitOnClose:true}); Ti.include("/controllers/products.js"); var productController = new ProductController(productWin); var productTab = Titanium.UI.createTab({ icon:'KS_nav_ui.png', title:'Products', window:productWin }); // Client tab var clientWin = Ti.UI.createWindow({exitOnClose:true}); Ti.include("/controllers/clients.js"); var clientController = new ClientController(clientWin); var clientTab = Titanium.UI.createTab({ icon:'KS_nav_views.png', title:'Clients', window:clientWin }); tabGroup.addTab(productTab); tabGroup.addTab(clientTab); tabGroup.open();
Now we can launch the emulator and enjoy our new MVC-based project.
You can download the sample code wrote and packed by Fabio Barbieri.
Links:
Part 1: Introduction
Part 2: Improvements
Part 4: Model and DB
Pingback: An MVC implementation for Appcelerator – Part 2: Improvements | PrimeGap()
Pingback: An MVC implementation for Appcelerator – Part 4: Model and DB | PrimeGap()