Bootstrap the overall framework of JavaScript plug-in architecture _javascript skills

Source: Internet
Author: User
Tags button type class definition event listener advantage

Examples of this article for you to introduce the JavaScript plug-in architecture knowledge points for your reference, the specific contents are as follows

1. JavaScript Plugin Architecture

The following are all the code for plug-in alert, each of which is defined in a scope similar to the following:

+function ($) {' Use strict '; 
 ALERT CLASS DEFINITION//====================== var dismiss = ' [data-dismiss= ' alert '] ' var alert = function (EL) { $ (EL). On (' Click ', Dismiss, this.close)} alert.version = ' 3.3.7 ' alert.transition_duration = Alert.prototype. Close = function (e) {var $this = $ (this) var selector = $this. attr (' Data-target ') if (!selector) {selector = $this . attr (' href ') selector = selector && selector.replace (/.* (? =#[^\s]*$)/, ')//strip for IE7} var $parent = $ (Selector = = ' # '?) []: selector) if (e) E.preventdefault () if (! $parent. length) {$parent = $this. Closest ('. Alert ')} $parent. Trigge R (E = $.  Event (' Close.bs.alert ') if (e.isdefaultprevented ()) return $parent. Removeclass (' in ') function removeelement () {// Detach from parent, fire event then clean up data $parent. Detach (). Trigger (' Closed.bs.alert '). Remove ()} $.support.tr
 Ansition && $parent. Hasclass (' fade ')? $parent. One (' Bstransitionend ', REMoveelement). Emulatetransitionend (alert.transition_duration): Removeelement ()}//Alert PLUGIN DEFINITION//= = = =================== function Plugin (option) {return This.each (function () {var $this = $ (this) var data = $this. dat A (' Bs.alert ') if (!data) $this. Data (' Bs.alert ', (data = new alert (this)) if (typeof option = = ' string ') data[option].c All ($this)}) ' var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.constructor = alert//alert NO CONFLICT/ /================= $.fn.alert.noconflict = function () {$.fn.alert = old return This}//alert Data-api//= =

=========== $ (document). On (' Click.bs.alert.data-api ', Dismiss, Alert.prototype.close)} (JQuery); 

 By assigning the alert class within the scope to the constructor property of the Alert object in jquery, the alert class can also be used outside the Iife action, such as this line of code var Alert = $.fn.alert.constructor

Bootstrap all plug-ins follow the same rules in development and provide the specification and basis for custom Plug-ins (three rules below):
1.HTML Layout rule: Layout rules based on element custom attributes, such as using custom attributes similar to Data-target
2.JavaScript implementation steps (all plug-ins follow the standard steps for jquery plug-in development, all events are consistent standards)
3. Plug-in invocation method (plug-in can be used in the form of HTML declarations or calls)

1.1 HTML Layout rules

Layout rules based on element custom attributes, similar to data-* custom properties

By default, all Plug-ins can be implemented by setting specific HTML code and corresponding custom attributes.
When the page is loaded, the JS code automatically detects the tags and automatically binds the corresponding events without adding additional code.

Clicking the button will close the warning box:

<div class= "alert" >
 <button type= "button" class= "Close" data-dismiss= "alert" ></button>
 <strong> warning!</strong> The item you entered is not legal!
</div>

Drop down menu: Add data-toggle= "Dropdown" property to the button button, and the default hidden Dropdown-menu appears when a stand-alone button

Example: Drop-down menu. html
<div class= "Btn-group" >
 <button type= "button" class= "btn Btn-default" data-toggle= " Dropdown ">
 my book <span class=" caret "></span>
 </button>
 <ul class=" Dropdown-menu ">
 <li><a href=" # "> Programming </a></li>
 <li><a href=" # "> Design </a></li>
 <li><a href= "#" > Deep </a></li>
 </ul>
</div>

1.2 JavaScript implementation steps (All plug-ins follow the standard steps of the jquery plug-in development, and all events remain uniform standards)

Bootstrap all JavaScript Plug-ins follow the unified implementation steps, maintenance convenience, custom plug-ins are also convenient, the steps are as follows:

1. Declare call function immediately, such as +function ($) {"Use strict";} (JQuery);

parameter to introduce a variable through the parameter, the advantage is: 1. A variable inside a function represents a local variable, rather than a character variable in a global variable that represents jquery, to prevent variable contamination. 2. Internal code is private code and external code cannot be accessed. Only through the third step, a plug-in (such as. fn.alert=) is set up on the. Fn to protect the internal code by allowing the entire plug-in to be exposed through the only excuse $.fn.alert.

The main purpose of the + in front of the function is to prevent the previous code (such as omitting a semicolon) from being terminated, causing the code to be considered one by the compiler, causing the code to run in error.

+function ($) {
 "use strict";

} (Window.jquery);

2. Define plug-in classes (or selectors) and related prototyping methods. Like Alert,prototype.close.

Define the plug-in class alert, and then define some prototype functions, such as the Close function method.
Define the selector first, and all elements that conform to the custom attribute can trigger the following event.

var dismiss = ' [data-dismiss= ' alert '] ';
var Alert = function (EL) {
 //incoming element, if the element has a custom attribute set on the dismiss, the Click event Triggers the Close method
 $ (EL) on the prototype. On (' Click ', Dismiss, this.close);
};
Alert.prototype.close = function (e) {

}

3. Define Plug-ins on jquery and reset plug-in constructors, such as $.fn.alert.constructor=alert

Define Plug-ins on jquery so that it can be used in the way of jquery. The plug-in name.

function Plugin (option) {return
 This.each (function () {
 var $this = $ (this)
 //Get the stored Alert object, If this is the first time the value of the variable data is undefined 
 var data = $this. Data (' Bs.alert ')
 //Cache not, just new an alert object, stored on the element's jquery object. Bs.alert ' data field
 if (!data) $this. Data (' Bs.alert ', (data = new alert (this))
 //Support for incoming method name parameters, this is Data.close ()
 if (typeof option = = ' string ') Data[option].call ($this)
 })
}
The jquery plug-in definition uses the standard approach, expands on FN, defines the alert plug-in
//$.fn.alert code (if defined) on jquery to continue using the old code after noconflict
//Back up the old code before the plugin, so that when the back of the conflict against the use of
var = $.fn.alert

$.fn.alert  = Plugin
///After the additional extension, Reset the plug-in's constructor (that is, the constructor property) so that you can query the plug-in's real-class functions through the constructor property, and the new operator is instantiated with no error
//js case sensitive. So here's the constructor is just a common attribute, unlike constructor, by assigning the alert class within the scope to the constructor attribute of the alert object in jquery, the alert class can also be used outside of the Iife action
$.fn.alert.constructor = Alert

If you do not declare the third step, the HTML declarative approach is also available. So the third step is designed specifically for someone who likes to trigger events with JS code. It should be noted that if the third step does not need, the fourth step of the side of the conflict will not be able to use the function ~

4. Anti-conflict handling (NOCONFLICT), such as $.fn.alert.noconflict

The goal is to have the bootstrap plug-in and other UI libraries have the same name Plug-ins.

$.fn.alert.noconflict = function () {
 //Restore previous code
 $.fn.alert = Old
 //Will $.fn.alert.noconflict () Alert plug-in set to bootstrap return this
}

For example, a library has the same name. Fn.alert plug-in, then the bootstrap before execution through the old first back up, and then execute. fn.alert.noConflict will restore the old object plug-in
Using the bootstrap alert plug-in, the alert plug-in of Bootstrap is transferred to another variable through the form of var alert = $.fn.alert.noconflict (), which continues to be used.

5. Bind various trigger events (DATA-API)

Because the default $.fn.alert extension functionality has been provided for jquery, you can manually write JS code to trigger the event.
This is primarily for declarative HTML triggering events. That is, the relevant custom attributes (such as data-dismiss= "alert") have been declared in the HTML document according to the layout rules, and then the default click event behavior is initialized through the code here.

/*
ALERT Data-api
This JavaScript code binds the Click Delegate Event listener on the document element and assigns a namespace
to the Click event The benefit of jquery binding events to document objects is the advantage of the JS event Agent
 * *
(document). On (' Click.bs.alert.data-api ', dismiss, Alert.prototype.close)

The benefits of namespaces: Http://suqing.iteye.com/blog/1533123, as follows

jQuery1.7 began, jquery introduced a new event binding mechanism, jquery. On () and off () two functions to uniformly handle event bindings, and also the best way for jquery to trigger DOM element events. Sometimes it is necessary to trigger the events manually, as well as to unpack the events from the DOM elements, such as:

$ ('. Item '). On (' click ', dothiscoolthing); 
$ ('. Item '). On (' click ', dothisothercoolthing); 
$ ('. Item '). Trigger (' click '); Two click events trigger 
$ ('. Item '). Off (' click ');//Two click events are untied  

Using Event Namespaces We can assign names to event handlers when creating events, and specify a specific function by this name when using trigger () and off (). When invoked, you can assign events flexibly by using different namespaces. Like what:

$ ('. Item '). On (' Click.navigate ', dothiscoolthing); 
$ ('. Item '). On (' click.notify ', dothisothercoolthing); 
$ ('. Item '). Trigger (' click.navigate '); Only methods with navigate this namespace will trigger 
$ ('. Item '). Off (' click.notify ');//Only the method with the Notify namespace will be untied  

You can also use more than one namespace, regardless of which name will take effect, through the namespace code specification (product. Module. event) to make the level of the event clearer:

$ ('. Item '). On (' click.navigate.notify ', dothiscoolthing); 
$ ('. Item '). Trigger (' click.navigate '); The Click event 
$ ('. Item ') will be triggered. Off (' click.notify ');//Will be untied Click event 


Resources:
http://www.andismith.com/blog/2011/11/on-and-off/
http://www.andismith.com/blog/2013/02/jquery-on-and-off-namespacing/

1.3 Plug-in Invocation method (Plug-in usage can be HTML declaration or invocation)

1. Plug-ins can be called JS Code, all provide a variety of calling mode (no parameter passing, passing object literal, directly into a need to execute a method name string)

$ ("#myModal"). modal ();
$ ("#myModal"). Modal ({keyboard:false});
$ ("#myModal"). Modal (' show ');

Each plug-in has a constructor attribute that represents the original constructor, such as the Fn.alert.Constructor (' selector '). Data (' BS. Plugin name ') to get instances of specific plug-ins

A 2.html declaration is a declaration data-* a custom attribute directly in HTML.

If you want to disable the method

Namespaces are disabled for all events in Data-api
$ (document). Off ('. Data-api ');
Disables the default behavior for a specific plug-in, disables the event in the namespace under the plug-in (
document). Off ('. Alert.data-api ');
Disables the alert plug-in's Click event
$ (document). Off (' Click.alert.data-api ');

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.