6 Events are where it happens!

This chapter covers

  • The event models as implemented by the browsers
  • The jQuery event model
  • Binding event handlers to DOM elements
  • Event delegation
  • Namespacing events
  • The Event object instance
  • Triggering event handlers under script control
  • Registering proactive event handlers

6.1 Understanding the browser event models

6.1.1 The DOM Level 0 Event Model


THE EVENT INSTANCE

if (!event) {
  event = window.event;
}
event = event || window.event;
var target = event.target || event.srcElement;

EVENT BUBBLING

function formatDate(date) {
  return (date.getHours() < 10 ? '0' : '') + date.getHours()  + ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':' +(date.getSeconds() < 10 ? '0' : '') + date.getSeconds() + '.' + (date.getMilliseconds() < 10 ? '00' : (date.getMilliseconds() < 100 ? '0' : '') ) + date.getMilliseconds();
}
var elements = document.getElementsByTagName('*');
for(var i = 0; i < elements.length; i++) {
  (function(current) {
    current.onclick = function(event)  {
      event = event || window.event;
      var target = event.target || event.srcElement;
    }
}) (elements[i]);
}

6.1.2 The DOM Level 2 Event Model


ESTABLISHING EVENT HANDLERS

addEventListener(eventType, listener, useCapture)
var element = document.getElementById('example');
element.addEventListener('click', function(event) {
  console.log('once');
}, false);
element.addEventListener('click', function(event) {
  console.log('twice');
},false);

EVENT PROPAGATION

true
capture handler
root to target

false
bubble handler
target to root

current.addEventListener('click', function(event) {
  console.log();
}, true);
current.addEventListener('click', function(event) {
  console.log();
}, false);

6.1.3 The Internet Explorer Model


attachEvent(eventName, handler)

6.2 The jQuery Event Model


  • Provides a unified method for establishing event handlers
  • Allows multiple handlers for each event type on each element
  • Uses standard event-type names: for example, click or mouseover
  • Passes the Event instance for the most-often-used properties
  • Provides unified methods for event canceling and default action blocking

6.2.1 Attaching event handlers with jQuery


$('img').on('click', function(event) {
  alert('hi there!');
});

on(eventType[, selector] [, data], handler)
on(eventsHash[, selector] [, data])
Parameters
eventType (String)
selector (String)
data (Any)
handler (Function)
eventsHash (Object)
Returns
The jQuery collection

$('#example')
  .on('click', function (event) {
    console.log('once');
  })
  .on('click', function (event) {
    console.log('twice');  
  });
$('img').on('click', null, null, function() {...});
$('img').on('click', function() {...});
$('button').on({
  click: function(event) {
    console.log('Button clicked!');
  },
  mouseenter: myFunctionHandler,
  mouseleave: myFunctionHandler
});
$('#my-button').on('click', {
  name: 'John Resig'
}, function (event) {
  console.log('The name is: ' + event.data.name);
});
$(document).on('mouseover', '#my-list li', function(event) {
  console.log('List item: ' + ($(this).index() + 1));
});

Events avaliable for listening

Events | | | |
----- | ---- | ---- |
blur | focusin | mousedown | mouseup
change | focusout | mouseenter | ready
click | keydown | mouseleave | resize
dbclick | keypress | mousemove | scroll
error | keyup | mouseout | select
focus | load | mouseover | submit
| | | unload


LISTENING FOR AN EVENT ONCE

one(eventType[, selector] [, data], handler )
one(eventsHash[, selector] [, data])
Returns
The jQuery collection


6.2.2 Removing event handlers


off(eventType[, selector] [, handler])
off(eventsHash, [, selector])
off()
Returns
The jQuery collection

$('*').off('.fred');
var $btn = $('#btn');
var counter = 1;

function logHandler() {
  console.log('click' + counter);
  counter++;
};
$('#btn-attach').on('click', function() {
  $btn.on('click', logHandler).text('Log');
});
$('#btn-remove').on('click', function(){
  $btn.off('click', logHandler).text('Does nothing');
});

6.2.3 Inspecting the Event instance


jQuery.Event properties
jQuery Event methods


6.2.4 Triggering event handlers


trigger(eventType[, data])
Parameters
event (String|jQuery.Event)
data (Any)
Returns
The jQuery collection

$('#foo').on('click', function(event, par1, par2, par3) {
  console.log(par1, par2, par3);
});
$('#foo').trigger('click', [1, 2, 3])

triggerHandler(eventType[, data])
Parameters
eventType (String)
data (Any)
Returns
Any.


HOVERING OVER ELEMENTS

$(element).mouseenter(function1).mouseleave(function2);

hover(enterHandler, leaveHandler)
hover(handler)
Parameters
enterHandler (Function)
leaveHandler (Function)
handler (Function)
Returns
The jQuery collection.

$('#outer2').hover(report);

6.2.6 How to create custom events


$('#btn').on('customEvent', function() {
  alert('customEvent');
});
$('#anotherBtn').click(function() {
  $('#btn').trigger('customEvent');
});

6.2.7 Namespacing events


$('.my-class').on('click.editMode', myFunction);
$('*').off('.editMode');
$('.elements').on('click.myApp.myName', myFunction);
$('.elements, .other-elements').trigger('.click.myApp');

6.3 Summary


This chapter introduced you the world of event handling.

你可能感兴趣的:(6 Events are where it happens!)