- Joined
- Dec 24, 2012
- Messages
- 88
- Reaction score
- 46
- First Language
- Dutch
- Primarily Uses
Making every variable global is the worst thing you can do. There's a reason many jQuery plugin creators wrap everything inside a function, it's to avoid any issues regarding compatibility. One function will overwrite the other, but then another does the same, thus, you end up with a broken mess.
What Bootstrap does in its Javascript modules is, it stores everything in a separate variable that's private, then adds a method that sets the old method as the default method.
Take this for example:
// ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this }What this does is, it sets the old method in a variable called old. When $('element').alert.noConflict() gets run, it sets the constructor back to the old one, and if I recall correctly, does so without setting it for any other element that uses the new method, but I could be wrong.
Another way is to store the old method in a submethod, like:
var oldMethod = MainObject.mainMethod;MainObject.mainMethod = function() {};MainObject.mainMethod.old = oldMethod;That way you don't needlessly expose everything that shouldn't be exposed.Like I said, it's bad practice to expose everything.
What Bootstrap does in its Javascript modules is, it stores everything in a separate variable that's private, then adds a method that sets the old method as the default method.
Take this for example:
// ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this }What this does is, it sets the old method in a variable called old. When $('element').alert.noConflict() gets run, it sets the constructor back to the old one, and if I recall correctly, does so without setting it for any other element that uses the new method, but I could be wrong.
Another way is to store the old method in a submethod, like:
var oldMethod = MainObject.mainMethod;MainObject.mainMethod = function() {};MainObject.mainMethod.old = oldMethod;That way you don't needlessly expose everything that shouldn't be exposed.Like I said, it's bad practice to expose everything.