0

我想知道如何在一行中绑定两个事件“click”和“touchstart”:

Engine.on("click"), function(){ aCode() }
Engine.on("touchstart", function(){ aCode() }

我期待这样的事情(因为它在其他一些框架中实现):

Engine.on("click touchstart", function(e){ aCode() });

我目前的解决方法是链接它们:

Engine.on("click", function(){Engine.emit("touchstart")});
Engine.on("touchstart", function() { aCode() }

有更好的做法吗?问题是在 iOS 上没有捕捉到点击,也没有在桌面上用鼠标触摸启动......显然我想以相同的方式处理事件,无论设备如何。

4

2 回答 2

2

[编辑]要以相同的方式处理单击和 touchstart->touchend,只需使用FastClick 覆盖 shim

只需添加:

FastClick = require('famous/inputs/FastClick');

那么这也适用于平板电脑:

anElement.on("click", function(){alert("Click caught")})

另一种选择是使用这个助手:

function onEvent(source, events, callback)
{
    for (var event in events)
    {
        source.on(events[event], function(e) {
            callback(e);
        });
    }
}

然后:

onEvent(Famous.Engine, ["click","touchstart"],function(){});
于 2014-05-05T08:02:03.720 回答
1

on()Famo.us 中的方法只接受一种事件类型。它不做任何 jQuery 风格的字符串处理来确定单独的事件。理论上你可以有一个名为的事件get to the chopper

然而,我在创建自定义视图时所做的是创建一个bindEvents()将所有事件侦听器组合在一起的函数。这些处理程序中的唯一代码是其他函数。如果我想以相同的方式对两个不同的事件做出反应,我只需对它们都使用相同的函数。

// An example Class demonstrating events - some off-topic parts omitted
function myLovelyHorseButton() {

    // Recomended Reading: https://famo.us/guides/dev/events.html

    this._eventInput = new EventHandler();
    this._eventOutput = new EventHandler();

    this._eventInput.pipe(this.sync);
    this.sync.pipe(this._eventInput);

    EventHandler.setInputHandler(this, this._eventInput);
    EventHandler.setOutputHandler(this, this._eventOutput);

    /** Set options & variables
    /* ...
    */

    // create event listeners for this specific instance
    _bindEvents.call(this);
};

// bind all the events for the button
function _bindEvents() {
    //Call event handlers with this set to owner.
    this._eventInput.bindThis(this);
    // listen for events
    this._eventInput.on('click', _handleClick);
    this._eventInput.on('touchstart', _handleClick);    //Same as 'click'
};

//  Nay to the console on click/touch
function _handleClick(event) {
    console.log('Nayyyyy!!!');
};


// create an instance of myLovelyHorseButton
var button = new myLovelyHorseButton;

// We would then add the button to the Render Tree
mainContext.add(button);

您不想使用当前使用的链接模式有一个很大的原因。那是因为通过在单击时发出一个 touchstart 事件,您可以推断那里会有一些代码对其进行操作。有一天,您可能会喝醉并决定“没有人在触摸设备上使用它!” 并删除ontouchstart处理程序。瞬间,您的代码对任何人都不起作用,无论是触摸还是鼠标。

TL;DR使用多个on()调用没有任何问题。

我希望这有帮助。

于 2014-05-04T13:05:02.507 回答