Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of $.fn.foo.Constructor = Foo in Twitter Bootstrap JS

All of the jQuery plugins for Twitter Bootstrap follow the same basic pattern of defining a class that controls the behavior of the plugin. Near the end, they do this:

$.fn.alert.Constructor = Alert

What is this doing?

I assume that this is defining a prototype constructor, but they use an uppercase C. Does case not matter here? Beyond that, I don't really understand what this is doing and how it's getting used by the plugin.

As an example, here is the Alert plugin: https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alert.js

like image 535
Nick Clark Avatar asked May 09 '12 23:05

Nick Clark


1 Answers

There is no magic here, Constructor (big C) as a property has no special meaning. THis is merely convention.

Basically they are using a class like structure to define the functionality

var Alert = function() {};
Alert.prototype.foo = function() {};

and exposing it through a non-class like interface.

$('#blurf').alert();

So this is simply a useful plugin convention. Each jQuery plugin defines itself primary method on the $.fn object, which has access to the constructors it needs via the closure. But the constructor itself is private to that closure. Assign it to $.fn.myplugin.Constructor simply makes that constructor accessible to other code, allowing you to have advanced control if necesary

var myAlert = new $.fn.alert.Constructor('Hello World'); // or something

Now you could something like this instead:

$.fn.alert.Alert = Alert;

This is, subjectively, ugly and redundant. And now you would have to translate or guess the property name that leads to the constructor. If you say each plugin is implemented with a single class, and each class constructor can be found at $.fn.myplugin.Constructor then you have a consistent interface for accessing the classes behind each plugin.

So again, this is merely convention, nothing too special about it.

like image 108
Alex Wayne Avatar answered Oct 15 '22 16:10

Alex Wayne