Search code examples
eventswebviewtitanium

Why does this Ti.UI.WebView.fireEvent() call throw an exception when a listener is present?


I create a new window with

var win = Ti.UI.createWindow({url:'page.js'});
win.listeners = {
   'type': function(e){ alert('test'); }
}
win.open();

Inside page.js, I add the specified listeners to a Ti.UI.WebView inside the window.

for (var type in win.listeners) {
    Ti.API.info(win.listeners[type])
    webView.addEventListener(type, win.listeners[type]);
}

Ti.API.info(win.listeners['type']) prints the function as "<KrollCallback: 0xb272160>"

A call to webView.fireEvent('type') executes fine if there are no listeners. But if I add listeners to the webView as above, the call to fireEvent throws an exception.

What is KrollCallback and why does fireEvent crash if there are listeners present?


Solution

  • The problem is that using url:'page.js' with createWindow() starts a new context. This type of setup will work if page.js is like this:

    exports.getWindow(config) {
    
       var webView = Ti.UI.createWebView({});
    
       for (var type in config.listeners) {
          webView.addEventListener(type, config.listeners[type]);
       }
    }
    

    Then, use the window like this:

    var win = require('page').getWindow({
       listeners = {
          'event_type': function(e){ alert('event_type test'); }
       }
    });
    
    win.open();