Skip to content

Instantly share code, notes, and snippets.

@krawaller
Created May 17, 2010 13:13
Show Gist options
  • Save krawaller/403742 to your computer and use it in GitHub Desktop.
Save krawaller/403742 to your computer and use it in GitHub Desktop.
var Test = {
name: 'test',
init: function(){
this.proxiedHandleEvents = $.proxy(this.handleEvents, this);
Ti.App.addEventListener('app', this.proxiedHandleEvents);
},
// Event cannon with callback fix.
fire: function(opts){
// If we're providing a callback, save a reference to it here
// to be able to call it when the response returns from the other side.
if (opts.func && opts.callback) {
var c = ++this.callbackCounter;
this.callbacks[c] = opts.callback;
// Must remap the callback to a callback id since we cannot
// pass functions between the native context and the webview context
opts.callback = c;
}
opts.from = this.name;
Ti.App.fireEvent(opts.to, opts);
},
// Event delegator
handleEvents: function(e){
// If the event object has a 'func' property,
// and that property is a function available in our singleton - call it.
if (typeof this[e.func] === 'function') {
// If a callback id is provided, the caller is waiting for a response.
// Overwrite the callback id with a replier function responding with that id.
// When our referenced function is done, it passes its result to the replier
// function, which makes sure the callback on the other side is passed that result.
if (e.callback) {
var c = e.callback,
self = this,
from = e.from;
e.callback = function(data){
self.fire({
data: data,
to: from, // Return to sender
callback: c // Call the callback with this id on the other side
});
};
}
if (!e.data) {
e.data = {};
}
// Call the specified function
this[e.func](e);
}
// Was it a callback - eg a response from the other side?
else
if (e.callback && this.callbacks[e.callback]) {
// Execute the correct callback and pass it the result object
this.callbacks[e.callback](e);
delete this.callbacks[e.callback];
}
},
checkWords: function(words){
this.fire({
to: 'app',
func: 'saveHighscore',
data: { words: words },
callback: function(e){
alert("We found " + e.data.correctWords.length + " correct words");
}
});
}
};
Test.init();
Test.checkWords(['hi', 'ho', 'foo']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment