Skip to content

Commit

Permalink
event fixes
Browse files Browse the repository at this point in the history
- Fix for issue fabiospampinato#57 with `null` delegates
- Object can be passed as the first parameter for `on` to register
multiple events at once
- Better `ready` handling.
- Don’t re-set node id if already set, and save cash node reference for
better performance
  • Loading branch information
shshaw committed Mar 4, 2016
1 parent 1fe6101 commit 69567ed
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 47 deletions.
57 changes: 34 additions & 23 deletions dist/cash.js
Expand Up @@ -412,17 +412,15 @@
}

function registerEvent(node, eventName, callback) {
var nid = cash(node).data(_eventId) || guid();
var cNode = cash(node), nid = cNode.data(_eventId);

cash(node).data(_eventId, nid);

if (!(nid in _eventCache)) {
_eventCache[nid] = {};
if (!nid) {
nid = guid();
cNode.data(_eventId, nid);
}

if (!(eventName in _eventCache[nid])) {
_eventCache[nid][eventName] = [];
}
_eventCache[nid] = _eventCache[nid] || {};
_eventCache[nid][eventName] = _eventCache[nid][eventName] || [];

_eventCache[nid][eventName].push(callback);
}
Expand All @@ -441,43 +439,56 @@
},

on: function (eventName, delegate, callback) {
var originalCallback;

if (!isString(eventName)) {
for (var key in eventName) {
if (eventName.hasOwnProperty(key)) {
this.on(key, delegate, eventName[key]);
}
}
return this;
}

if (isFunction(delegate)) {
callback = delegate;
delegate = null;
}

return this.each(function (v) {
registerEvent(cash(v), eventName, callback);
v.addEventListener(eventName, callback);
});
if (eventName === "ready") {
onReady(callback);return this;
}

return this.each(function (v) {
function handler(e) {
if (delegate) {
originalCallback = callback;

callback = function (e) {
var t = e.target;

if (matches(t, delegate)) {
callback.call(t);
originalCallback.call(t);
} else {
while (!matches(t, delegate)) {
if (t === v) {
if (t === this) {
return (t = false);
}
t = t.parentNode;
}

if (t) {
callback.call(t);
originalCallback.call(t);
}
}
}
};
}

registerEvent(cash(v), eventName, handler);
v.addEventListener(eventName, handler);
return this.each(function (v) {
registerEvent(v, eventName, callback);
v.addEventListener(eventName, callback);
});
},

ready: function (callback) {
onReady(callback);
},
ready: onReady,

trigger: function (eventName) {
var evt = doc.createEvent("HTMLEvents");
Expand Down
2 changes: 1 addition & 1 deletion dist/cash.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 69567ed

Please sign in to comment.