Noodlecode parody of spaghetti code

Titanium app components interaction using events and callbacks

Events

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() {
    webservice.getMoreData();
});
btn.addEventListener('click', function() {
    loadingIndicator.show();
});

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

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

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

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');

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

Categories: Notes

Windows Phone app dev note » « Object oriented Javascript with CommonJS in Titanium app

1 Comment

  1. What module did you use to parse the id3 tag? 🙂

Leave a Reply

Your email address will not be published.

*

Copyright © 2017 Noodlecode