Skip to content

Instantly share code, notes, and snippets.

@tonylukasavage
Created August 5, 2013 19:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tonylukasavage/6158759 to your computer and use it in GitHub Desktop.
Save tonylukasavage/6158759 to your computer and use it in GitHub Desktop.
inheriting event handlers in Alloy
// The base controller event handler, which will get overridden by the derived one
exports.doClick = function(e) {
alert('base click handler');
};
// We have to wait until the object is initialized before applying the event listener. This is so
// the derived listener is used, not the base one. Also, "$" must be used instead of "exports", to
// ensure that the overridden instance of the controller's "doClick" is used, not the exported
// version of the function from the base controller.
exports.init = function(e) {
$.button.addEventListener('click', $.doClick);
};
'#base': {
backgroundColor: '#faa',
fullscreen: false
}
<Alloy>
<Window>
<Button id="button">click me</Button>
</Window>
</Alloy>
exports.baseController = 'base';
// the derived event handler that we will see execute
exports.doClick = function(e) {
alert('derived click handler');
};
function openWindow(e) {
// create the controller instance
var derived = Alloy.createController('derived');
// call the init() function, which is what allows us the use inheritance to determine which event handler
// this instance of the controller will use. We must do this after the controller instance has been created,
// as detailed in the comments in the base.js file.
derived.init();
// open the controller's window, as defined in the base.xml file
derived.getView().open();
}
$.index.open();
'Label': {
touchEnabled: false
}
'#index': {
backgroundColor: '#fff',
fullscreen: false,
exitOnClose: true
}
<Alloy>
<Window onClick="openWindow">
<Label>Click anywhere to open derived window</Label>
</Window>
</Alloy>
@juncoding
Copy link

Hi, Tony,

Great thanks.

I tried to call parent function in child, but not found how to do this.

Example:

parent.js

$.test = function() {
alert('parent');
}

child.js

exports.baseController = 'parent';

$.test = function() {

// How to do if I want to call parent test function here ?
// I tried to use exports.baseController.test(); but met runtime error said cannot find variable test.

}

Please advise.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment