From 29a40049fb9234091da47a7c674189b936094f59 Mon Sep 17 00:00:00 2001 From: Matthieu Dumont Date: Fri, 9 Dec 2016 15:29:37 +0100 Subject: [PATCH] feat(noConflict): new method to avoid window conflict Closes #133 --- src/standalone/index.js | 11 +++++++++++ test/unit/standalone_spec.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/standalone/index.js b/src/standalone/index.js index 68201bb2d..2d4681bcc 100644 --- a/src/standalone/index.js +++ b/src/standalone/index.js @@ -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; diff --git a/test/unit/standalone_spec.js b/test/unit/standalone_spec.js index cfbfced24..83becb388 100644 --- a/test/unit/standalone_spec.js +++ b/test/unit/standalone_spec.js @@ -91,3 +91,37 @@ describe('Typeahead', function() { }); }); + +describe('noConflict()', function() { + it('should restore the previous value of autocomplete', function() { + 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); + }); +});