Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Создание глобального события (https://javascript.ru/forum/jquery/31670-sozdanie-globalnogo-sobytiya.html)

kez 16.09.2012 17:04

Создание глобального события
 
У mootools фреймворка в примерах есть создание глобального события, на которое можно потом подписаться

Код:

Element.Events.shiftclick = {
    base: 'click', // the base event type
    condition: function(event){ //a function to perform additional checks
        return (event.shift == true); // this means the event is free to fire
    }
};

$('myInput').addEvent('shiftclick', function(event){
    log('the user clicked the left mouse button while holding the shift key');
});

У jQuery всегда использовал события на селектор

Код:

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
});

Но хотелось бы сделать аналог события, как у mootools...Хотелось бы просто делать bind на собственное событие...

Прошу совета!

walik 17.09.2012 11:49

Не знаю как насчет собственного события, но можно так сделать:
<!DOCTYPE HTML>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
  </head>
  <body>
    <script>
      $.fn.shiftclick = function(fn) {
        return $(this).click(function(e) {
        	if (e.shiftKey)
              	fn.call(this);
        });
      }
        
        $(function() {
          $('body').shiftclick(function() {
          	alert('a');
          });
        });
    </script>
    Click Me
  </body>
</html>


Часовой пояс GMT +3, время: 15:41.