Skip to content

Commit

Permalink
feat(noConflict): new method to avoid window conflict
Browse files Browse the repository at this point in the history
Closes #133
  • Loading branch information
Jerska committed Dec 9, 2016
1 parent b587fa2 commit 6b841f5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/standalone/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,15 @@ function autocomplete(selector, options, datasets, typeaheadObject) {

autocomplete.sources = Typeahead.sources;

var wasAutocompleteSet = 'autocomplete' in window;
var oldAutocomplete = window.autocomplete;
autocomplete.noConflict = function noConflict() {
if (wasAutocompleteSet) {
window.autocomplete = oldAutocomplete;
} else {
delete window.autocomplete;
}
return autocomplete;
};

module.exports = autocomplete;
35 changes: 35 additions & 0 deletions test/unit/standalone_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,38 @@ describe('Typeahead', function() {
});

});

describe('noConflict()', function() {
it ('should restore the previous value of autocomplete', function () {
window = {};
window.autocomplete = 'test';

// Rerequire autocomplete
delete require.cache[require.resolve('../../src/standalone/index.js')]
var autocomplete = require('../../src/standalone/index.js');

expect(window.autocomplete).toBe('test');
window.autocomplete = autocomplete;

var aa = autocomplete.noConflict();
expect(aa).toBe(autocomplete);
expect(window.autocomplete).toBe('test');
});

it ('should delete window.autocomplete if it wasn\'t set', function () {
if ('autocomplete' in window) {
delete window.autocomplete;
}

// Rerequire autocomplete
delete require.cache[require.resolve('../../src/standalone/index.js')]
var autocomplete = require('../../src/standalone/index.js');

expect('autocomplete' in window).toBe(false);
window.autocomplete = autocomplete;

var aa = autocomplete.noConflict();
expect(aa).toBe(autocomplete);
expect('autocomplete' in window).toBe(false);
});
});

0 comments on commit 6b841f5

Please sign in to comment.