Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jQuery internals

jQuery internals

An overview on how jQuery code is organized, what parts are good and bad, and insights on the plugin system and one of the most complex parts of it: the internal event handling.

Miguel Jiménez

April 16, 2015
Tweet

More Decks by Miguel Jiménez

Other Decks in Programming

Transcript

  1. Selector engine • Selection is usually tried first with qSA

    ◦ Some μ-optimizations built-in (e.g.: #id). • Failure on it triggers full Sizzle engine ◦ :first-child on IE7 ◦ :visible on any browser • Some valid selectors are also ran by Sizzle!
  2. The $ function var body = $('body'); window.$ = window.jQuery;

    jQuery = function(selector, context) { return new jQuery.fn.init(selector, context); };
  3. The “fn” object jQuery.fn = jQuery.prototype = {...}; jQuery.fn.init =

    function(selector, context) { ... (some magic with selectors) ... }; jQuery.fn.init.prototype = jQuery.fn;
  4. Why? • $ is shorter than jQuery • $.fn is

    way shorter than jQuery.prototype • Instances are created regardless of the “new” keyword • “init” prototype is the same as “$” prototype, so the inner trick looks transparent
  5. jQuery.event.add: generic handler type ('click') callback (method) element (<DIV>) var

    eventHandle = function(e) { return jQuery.event.dispatch(...); }; element.addEventListener(type, eventHandle, false);
  6. jQuery.event.add: store callback type ('click') callback (method) element (<DIV>) {

    'click': [function() {}, ...], 'dblclick': [function() {}, ...] } events[type].push(method); dataPriv(element)
  7. Triggering an event! type ('click') callback (method) element (<DIV>) var

    eventHandle = function(e) { return jQuery.event.dispatch(...); }; element.addEventListener(type, eventHandle, false); { 'click': [function() {}, ...], 'dblclick': [function() {}, ...] } events[type].push(method); dataPriv(element) dataPriv(this) events['click'] Iterate calling methods Sanitize event
  8. Why? • W3C event model is somehow crappy ◦ Detach

    all events at once! ◦ List events attached! • Standardizes interface for attaching and triggering native & non-native methods • Solves quirks on the “event” object