Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 2f91cfd

Browse files
chrisirhcvojtajina
authored andcommitted
fix(jqLite): support unbind self within handler
If an event handler unbinds itself, the next event handler on the same event and element doesn't get executed. This works fine in jQuery, and since jqLite doesn't support .one, this might be a common use case.
1 parent d5c5e2b commit 2f91cfd

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/jqLite.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,10 @@ function createEventHandler(element, events) {
645645
return event.defaultPrevented || event.returnValue === false;
646646
};
647647

648-
forEach(events[type || event.type], function(fn) {
648+
// Copy event handlers in case event handlers array is modified during execution.
649+
var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
650+
651+
forEach(eventHandlersCopy, function(fn) {
649652
fn.call(element, event);
650653
});
651654

test/jqLiteSpec.js

+20
Original file line numberDiff line numberDiff line change
@@ -1120,6 +1120,26 @@ describe('jqLite', function() {
11201120
});
11211121

11221122

1123+
it('should deregister specific listener within the listener and call subsequent listeners', function() {
1124+
var aElem = jqLite(a),
1125+
clickSpy = jasmine.createSpy('click'),
1126+
clickOnceSpy = jasmine.createSpy('clickOnce').andCallFake(function() {
1127+
aElem.off('click', clickOnceSpy);
1128+
});
1129+
1130+
aElem.on('click', clickOnceSpy);
1131+
aElem.on('click', clickSpy);
1132+
1133+
browserTrigger(a, 'click');
1134+
expect(clickOnceSpy).toHaveBeenCalledOnce();
1135+
expect(clickSpy).toHaveBeenCalledOnce();
1136+
1137+
browserTrigger(a, 'click');
1138+
expect(clickOnceSpy).toHaveBeenCalledOnce();
1139+
expect(clickSpy.callCount).toBe(2);
1140+
});
1141+
1142+
11231143
it('should deregister specific listener for multiple types separated by spaces', function() {
11241144
var aElem = jqLite(a),
11251145
masterSpy = jasmine.createSpy('master'),

0 commit comments

Comments
 (0)