Skip to content

Instantly share code, notes, and snippets.

@davidecassenti
Created February 18, 2014 15:44
Show Gist options
  • Save davidecassenti/9073463 to your computer and use it in GitHub Desktop.
Save davidecassenti/9073463 to your computer and use it in GitHub Desktop.
Appcelerator Alloy | Using a common library that can access multiple Alloy views
var HomeLibrary = require('home_library');
// HomeController is the name that will be used inside
// the XML view to access the methods of the library
var HomeController = new HomeLibrary('home1', $);
<Alloy>
<Window id="home" backgroundColor="yellow">
<Label id="mylabel" top="30">Home 1</Label>
<Button id="mybutton" onClick="HomeController.button" top="60">Click</Button>
<Button id="close" onClick="HomeController.close" top="90">Close</Button>
</Window>
</Alloy>
var HomeLibrary = require('home_library');
var HomeController = new HomeLibrary('home2', $);
<Alloy>
<Window id="home" backgroundColor="pink">
<Label id="mylabel" top="30">Home 2</Label>
<Button id="close" onClick="HomeController.close" top="60">Close</Button>
</Window>
</Alloy>
//
// NOTE: this file is in the /lib/ directory
//
var $ = null; // redefine the $, so that we use the specific subview UI elements
var controller = null;
// Constructor
function HomeLibrary(_controller, _$) {
// TODO should make sure that the parameters are passed
$ = _$; // replace the $
controller = _controller; // get the controller name
}
// This function will be used in the view home1.xml only
HomeLibrary.prototype.button = function() {
alert('Clicked!');
};
// This function will be used by both views
HomeLibrary.prototype.close = function() {
// since $ is redefined, we can access the UI views as usual
$.home.close();
};
module.exports = HomeLibrary;
$.index.open();
// open the controller home1
function open1() {
var home = Alloy.createController('home1').getView('home');
home.open();
}
// open the controller home2
function open2() {
var home = Alloy.createController('home2').getView('home');
home.open();
}
<Alloy>
<Window>
<Button onClick="open1" top="30">Open 1</Button>
<Button onClick="open2" top="60">Open 2</Button>
</Window>
</Alloy>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment