19
James Greene http://jamesgreene.net/

Leveraging jQuery's Special Events API (JSConf 2012)

Embed Size (px)

Citation preview

James Greene

http://jamesgreene.net/

“Bang, Bang”

(Just kidding!) 2

The Problem

I desire…

3

$("body").on("textSelect", function($event) {

console.log("Text was selected!");

});

4

WANTED!

DEAD OR ALIVE

$("body").on("textSelect", function($event) {

console.log("Text was selected!");

});

$("body").on("mouseup", function($event) {

if (window.getSelection().rangeCount > 0) {

$("body").trigger("textSelect");

}

}

5

Cheesy!

$.fn.onTextSelect = function(callback) {

this.on("mouseup", function($event) {

if (window.getSelection().rangeCount > 0) {

callback($event);

}

}

}

$("body").onTextSelect(function($event) {

console.log("Text was selected!");

});

6

Better…?

jQuery Event System

Special Events API

7

jQuery 1.3:

Special Events API

…but no official documentation

jQuery 1.7:

Major overhaul to Special Events API

…but still no official documentation

Official documentation? Now in progress….

Brief History

8

1.Allow hooks for “fixing” events

2.Allow for creation of custom events

ready

mouseenter

mouseleave

*

Responsibilities

9

$.event.special.MyEvent = {

noBubble: false,

bindType: "otherEventType",

delegateType: "otherEventType",

handle: function($event, data) { … },

};

Custom Event: Syntax #1

NOTE: Almost all of these are optional to set (in varying combinations).10

$.event.special.MyEvent = {

noBubble: false,

setup: function(data, namespaces, handler) { … },

teardown: function() { … },

add: function(handleObj) { … },

remove: function(handleObj) { … },

trigger: function($event, data) { … },

_default: function($event, data) { … }

};

Custom Event: Syntax #2

NOTE: Almost all of these are optional to set (in varying combinations).11

Demo Time

Making the magic happen!

12

Usage:

$(…).on("multiclick", { clicks: 3 },

function($event) {

console.log("Thrice!");

}

);

Demo pages:

Basic

Nested elements

Code:

http://github.com/JamesMGreene/jquery.multiclick/

Demo #1: multiclick

13

Usage:

$(…).on("textSelect", function($event) {

console.log("Text was selected!");

});

Demo page:

Basic

Code:

http://github.com/JamesMGreene/jquery.textSelect/

Demo #2: textSelect

14

throw new RangeError(

"A demo does not exist at this index");

Demo #3: swipe

15

Aftermath

Lessons Learned

16

Surprise!

Textual selection event was added to IE9+.

Sort of….

17

Lessons Learned

Special Events API is a dependency of jQuery Mobile:

tap

scrollstart / scrollstop

swipe / swipeleft / swiperight

orientationchange

throttledresize

18

Lessons Learned

19

Questions?

James Greenehttp://jamesgreene.net/