Skip to content

Commit

Permalink
perf(jqLite): avoid repeated add/removeAttribute in jqLiteRemoveClass
Browse files Browse the repository at this point in the history
  • Loading branch information
jbedard committed Sep 9, 2017
1 parent 21a2f4b commit 007a7ef
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/jqLite.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,13 +420,15 @@ function jqLiteHasClass(element, selector) {

function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ');

forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ')
.replace(' ' + trim(cssClass) + ' ', ' '))
);
cssClass = trim(cssClass);
existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' ');
});

element.setAttribute('class', trim(existingClasses));
}
}

Expand Down
28 changes: 28 additions & 0 deletions test/jqLiteSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,20 @@ describe('jqLite', function() {
});


it('should only get/set the attribute once when multiple classes added', function() {
var fakeElement = {
nodeType: 1,
setAttribute: jasmine.createSpy(),
getAttribute: jasmine.createSpy().and.returnValue('')
};
var jqA = jqLite(fakeElement);

jqA.addClass('foo bar baz');
expect(fakeElement.getAttribute).toHaveBeenCalledOnceWith('class');
expect(fakeElement.setAttribute).toHaveBeenCalledOnceWith('class', 'foo bar baz');
});


it('should not add duplicate classes', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
Expand Down Expand Up @@ -1031,6 +1045,20 @@ describe('jqLite', function() {
jqA.removeClass('foo baz noexistent');
expect(a.className).toBe('bar');
});


it('should get/set the attribute once when removing multiple classes', function() {
var fakeElement = {
nodeType: 1,
setAttribute: jasmine.createSpy(),
getAttribute: jasmine.createSpy().and.returnValue('foo bar baz')
};
var jqA = jqLite(fakeElement);

jqA.removeClass('foo baz noexistent');
expect(fakeElement.getAttribute).toHaveBeenCalledOnceWith('class');
expect(fakeElement.setAttribute).toHaveBeenCalledOnceWith('class', 'bar');
});
});
});

Expand Down

0 comments on commit 007a7ef

Please sign in to comment.