【问题标题】:Titanium/ Alloy: Add event listener to a windowTitanium/Alloy:向窗口添加事件监听器
【发布时间】:2017-08-13 19:19:57
【问题描述】:

我在 index.js 中有以下代码:

var win = Alloy.createController('foo').getView();
win.open();
win.addEventListener('exampleEvent', function () {
    Ti.API.info('Event Run!'); // does not seem to run
});

关于 foo.js 我有以下内容:

function runEvent() {
    $.trigger('exampleEvent');
    $.getView().close();
}

// execute runEvent() somewhere later

但是,事件监听器中的函数似乎没有运行。

我做错了什么?

【问题讨论】:

    标签: titanium appcelerator appcelerator-titanium titanium-alloy appcelerator-alloy


    【解决方案1】:

    您错过了一点,即只能在控制器上添加自定义事件,而不能在视图上添加。

    var win = Alloy.createController('foo').getView();
    

    在这一行中,您通过在 win 变量中使用 getView() 来保持视图。

    现在应该是这样的:

    var win = Alloy.createController('foo');
    
    win.on('exampleEvent', function () {
        Ti.API.info('Event Run!'); // it will run now as you have added custom event on controller (means $ in .js file) itself.
    });
    
    // now you can get the top-most view (which is a window in this case) and can further use open() method on window
    win.getView().open();
    

    foo.js 将保持不变:

    function runEvent() {
        $.trigger('exampleEvent');
        $.getView().close();
    }
    
    // execute runEvent() somewhere later
    

    【讨论】:

      【解决方案2】:

      就我而言,我使用的是

      var controller = Alloy.createController('myController');
      controller.addEventListener("customEvent",function(){});
      

      过去一个小时我一直在打我的头......

      在@PrashantSaini 提出的之上,控制器对象上没有addEventListener,控制器具有on 函数,所以应该是:

      controller.on("customEvent",function(){});
      

      更新

      我的回答是提醒控制器对象上没有 addeventlistener。

      【讨论】:

      • 我看不出这与@Prashant Sainj 的回答有何不同
      猜你喜欢
      • 2012-02-21
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多