Tonton MyTV dilengkapi intisari rancangan pada smart TV bermula RM4.99 sebulan. Selanjutnya →

Titanium app components interaction using events and callbacks

Rabu, 14 Ogos 2013, 2:14 pm0


Events are used to broadcast an action happened to zero or many receipients.

Example, in a list of items, when user click on ‘Load more’ button at the bottom of the list, at least 2 actions need to be executed simultaneously – show the loading indicator and start fetching more data from web service.

var btn = Ti.UI.createButton({ title: 'Load more' });
btn.addEventListener('click', function() {
btn.addEventListener('click', function() {;

Another example is, when the loading data process is done, an event is being broadcasted.

webservice.addEventListener('data_received', function(data) {
    if (win) {

Here, if the current window is still opened, at least one receipient will respond to that event, or else there’s no receipient at all.


Callbacks are used as an immediate respond to be called right after a block of code has done executing. Callbacks can only be attached to only one function call – only have one receipient that respond to it. Callbacks are suitable to use on a function call that will return result asynchronously, but return response differently everytime.

Example, when calling a function to retrieve ID3 tag info from an MP3 file, a callback is passed when the retrieve process is done.

var ID3 = require('module.id3tag');

	file: Ti.Filesystem.getFile('song.mp3'),
	success: function(e) {'Song artist: ' + e.artist);

Tulis komen: