Getting Titanium CurrentWindow To Work Under CommonJS

Getting Titanium CurrentWindow To Work Under CommonJS

Hold on Cowboy

This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.

Appcelerator is a moving target, developed and changing pretty fast. The old way was using the **url: ** property of a window to open up a new screen with a javascript screen.

Old and Busted

var window = Ti.UI.createWindow({
    url: 'screen.js'
});

Another Old Way

Then came the Tweetanium structure, while a solid way to set up, it’s not the route Appcelerator is recommending anymore.

See my post for more information on the Tweetanium Setup

The New Hostness

Appcelerator is now recommending the CommonJS route just like that found in Node.js. But you’ll find all kinds of people not able to find the current window.

How do you find the currentWindow?

First I set up a globals.js module that I’ll use to hold global information.

/**
 * Global options
 *
 * @author Shane A. Stillwell
 */

var globals = {
    currentWindow: null
};

exports.getOption = function(key) {
    return globals[key];
};

exports.setOption = function(key, value) {
    globals[key] = value;
    return;
};

exports.getAll = function() {
    return globals;
};

Then I need to add event listeners when the window changes, I’m currently using a TabGroup for this project, so right after I declare a TabGroup I attach an eventlistener it.

// Require the globals.js file (it'll be a singleton)
var globals = require('/modules/globals');

//create base proxy object and component wrapper
var self = new Ti.UI.createTabGroup();

// Add event listener to set the currentWindow in globals
self.addEventListener('focus', function(e) {
    Ti.API.info(e.tab.getWindow());
    globals.setOption('currentWindow', e.tab.getWindow());
});

Now when I want to know the current window I just call this

// Require the globals.js file (it'll be a singleton)
var globals = require('/modules/globals');

var currentWindow = globals.getOption('currentWindow');

Now I can remove child views, close, animate, etc. whatever