Skip to content

Commit

Permalink
Add helper for listening to jQuery events
Browse files Browse the repository at this point in the history
This helper can be used when another module registers $.event.special events and you need to listen to those events with can-dom-events.
  • Loading branch information
chasenlehara committed Mar 12, 2018
1 parent 7f25ffe commit 9eace76
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions can-dom-events-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,5 @@ unit.test('domEvents.addDelegateListener handles document correctly', function (
require('./helpers/make-event-registry-test');
require('./helpers/add-event-compat-test');
require('./helpers/add-event-jquery-test');
require('./helpers/add-jquery-events-test');
require('./helpers/util-test');
32 changes: 32 additions & 0 deletions helpers/add-jquery-events-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
var unit = require('steal-qunit');
var $ = require('jquery');
var addEvents = require('./add-jquery-events');
var domEvents = require('../can-dom-events');

unit.module('add-jquery-events');

unit.test('should work with the jQuery', function (assert) {
assert.expect(3);

var divElement = document.createElement('div');

var eventType = 'draginit';
var handler = function (event) {
assert.equal(event.target, divElement, 'div should be the target');
assert.equal(event.type, eventType, 'event type should match custom event type');
assert.equal(event.handleObj.handler, handler, 'callback should be the passed handler');
};

// Set up the special event
$.event.special[eventType] = {};

// Bridge can-dom-events + jQuery
var removeEvents = addEvents($);

// Listen to and trigger the event; handler should run
domEvents.addEventListener(divElement, eventType, handler);
$(divElement).trigger(eventType);

// Clean up after ourselves :)
removeEvents();
});
28 changes: 28 additions & 0 deletions helpers/add-jquery-events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

var domEvents = require('../can-dom-events');

module.exports = function addJQueryEvents(jQuery) {
var jQueryEvents = jQuery.event.special;
var removeEvents = [];

for (var eventType in jQueryEvents) {
var eventDefinition = {
defaultEventType: eventType,
addEventListener: function (target, eventType, handler) {
$(target).on(eventType, handler);
},
removeEventListener: function (target, eventType, handler) {
$(target).off(eventType, handler);
}
};
var removeEvent = domEvents.addEvent(eventDefinition);
removeEvents.push(removeEvent);
}

return function removeJQueryEvents() {
removeEvents.forEach(function(removeEvent) {
removeEvent();
});
};
};

0 comments on commit 9eace76

Please sign in to comment.