Forin
Forin

Reputation: 1619

YUI + jQuery long press action and default click

I currently write project using YUI(app framework). A have some actions for each elements( going to another page, clear etc.). I want to add long press action to each button. Unfortunately YUI doesn't support this kind of stuff. I found solution in jQuery:

 var pressTimer

$("a").mouseup(function(){
  clearTimeout(pressTimer)
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... your code ...},1000)
  return false; 
});

And here is my question. How to add this feature to my current code? Writing new function doesn't work, so does adding this code to existing function.

//edited My code looks like this:

//stuff
events: {
'.button': {
click: 'select'
}
},

And then there is select function:

select: function (e) {
//code
}

Upvotes: 0

Views: 170

Answers (1)

juandopazo
juandopazo

Reputation: 6329

YUI has a concept called Synthetic events. These events are fake DOM events that you define to behave in a similar way as $(foo).trigger('myFooEvent') in jQuery. Defining a synthetic event is just a matter of calling Y.Event.define(). In your case it would look something like this:

Y.Event.define('longpress', {
  on: function (node, sub, notifier) {
    var timeout;

    sub._downHandle = node.on('mousedown', function (e) {
      timeout = setTimeout(function () {
        notifier.fire('longpress', {domEvent: e});
      }, 1000);
    });
    sub._upHandle = node.on('mouseup', function () {
      clearTimeout(timeout);
    });
  },
  detach: function (node, sub) {
    sub._downHandle.detach();
    sub._upHandle.detach();
  }
});

After defining a synthetic event all you have to do to use it is call node.on('myevent'). For example: Y.one('#foo').on('longpress', fn).

The YUI App Framework uses event delegation, so you're going to have to add support for event delegation to your synthetic event. I suggest that you read the Synthetic Events section of the Event User Guide and follow the Creating an Arrow Event for DOM subscription example.

After setting up your event you should be able to use it in the app framework as you would any other event:

events: {
  '.button': {
    'longpress': fn
  }
}

Upvotes: 1

Related Questions