Reputation: 2296
A common explanation of how to pass events from a Titanium webview involves calling Ti.App.fireEvent() from the HTML in the webview. But, I would like to listen to the webview itself instead of the global Ti.App object, so that duplicate events from different webviews won't trigger inappropriate code for the context.
Eg. if I listen to Ti.App for the "OK_BUTTON" event, it will mean something different depending on where in the flow it is being called. So, I would have to remove and add new listeners for each context.
There is a documented way to pass events directly from the webview using a normal HTML anchor tag with the undefined protocol "xxxx://" and catching the ensuing error event in Titanium. Is there a cleaner way to do this yet? It would be nice to keep the "error" event for errors as intended.
Upvotes: 0
Views: 1634
Reputation: 2296
Here is a basic utility module that assigns an id to a webview and provides a function fireEvent() to webview context that will trigger an event on the webView object in Titanium.
var listenerWebViews = {};
exports.createListenerWebView = function(config) {
var id = createRandomString();
var webView = Ti.UI.createWebView(config);
webView.listenerId = id;
webView.evalJS('function fireEvent(type, e) { var f = { originalType:type, listenerId:"'+id+'"}; Ti.App.fireEvent("WEBVIEW_LISTENER_EVENT", f); }');
listenerWebViews[id] = webView;
var oldRemoveFunction = webView.remove;
webView.remove = function(){
listenerWebViews[id] = null;
oldRemoveFunction();
}
return webView;
}
Ti.App.addEventListener("WEBVIEW_LISTENER_EVENT", function(e){
var webView = listenerWebViews[e.listenerId];
if (webView) {
webView.fireEvent(e.originalType, e);
}
});
With that module included, this works:
var view = module.createListenerWebView({
url: 'myPage.html'
});
view.addEventListener('my_type', function(){
alert('webview event!');
});
view.evalJS("fireEvent('my_type');");
Upvotes: 0
Reputation: 405
I think you'll need to use Ti.App.fireEvent()
from the webview but add data identifying the source webview to the event.
e.g. assign a unique id to each of your webviews and pass that into the webview by doing an 'evalJS()' in the webview's 'load' event handler. (Or by setting the id in your html if you have Titanium generating that)
Upvotes: 1