JS Component Series-Package your own JS components, you can!

Source: Internet
Author: User
Tags toastr

Preface: Prior to sharing the experience of so many bootstrap components, this blogger intends to study the extension and encapsulation of the next JS component, and we will feel the next jquery offering US $. Extend Magic, see how we customize our components, such as we want to extend a $ ("#id"). Myjscontrol ({}) do our own component, how do we do it, don't worry, we take a slow look at the process.

I. Expansion of existing components 1, requirements background

Many times, we use the Jquery.ajax way to send requests to the background, such as

  $.ajax ({type:  "POST"  "/user/edit"  function   (data, status)                        { if  (Status = = "Success" ) {                        Toastr.success ( ' submit data succeeded '  "#tb_aaa"). Bootstraptable (' Refresh '  function   (e) {}, complete:  function   () {                }            });

This code is too common, and this time we have a requirement: We do not want to write Error:function (e) {} This code every time we call AJAX requests. But we want it to output AJAX error messages to the browser every time, so that users can see them. What do we do?

2. Principle of realization

To achieve these results is not difficult, we can encapsulate the $.ajax ({}) layer, in the encapsulated public method to define the error corresponding event can be. It is true that this will meet our requirements, but it is not perfect, for the simple reason: 1 It is not efficient enough to encapsulate a layer on the basis of jquery, 2) It needs to change the caller's habit, and each time we call Ajax we need to write it in accordance with the rules of the method we define, not directly with the native $.ajax ( {}) This is what we don't want to see.

In that case, how do we not encapsulate the control, but also to achieve the above requirements? The answer is to extend the native jquery.ajax through our $.extend.

In fact, it is not difficult to achieve, through the following section of code to achieve our requirements.

(function ($) {    //1. Get the $.ajax object    var_ajax =$.ajax; $.ajax=function(options) {//2. Define the default error handling method each time a call is sent to the AJAX request        varfn ={error:function(XMLHttpRequest, Textstatus, Errorthrown) {toastr.error (Xmlhttprequest.responsetext,' Error message ', {closeButton:true, timeout:0, Positionclass: ' Toast-top-full-width ' }); }, Success:function(data, textstatus) {}, Beforesend:function(XHR) {}, complete:function(XHR, TS) {}}//3. If you write the error handling method at the time of the call, do not use the default        if(options.error) {Fn.error=Options.error; }        if(options.success) {fn.success=options.success; }        if(options.beforesend) {fn.beforesend=Options.beforesend; }        if(options.complete) {Fn.complete=Options.complete; }        //4. Extend the native $.ajax method to return the latest parameters        var_options =$.extend (options, {error:function(XMLHttpRequest, Textstatus, Errorthrown) {fn.error (XMLHttpRequest, Textstatus, Errorthrown); }, Success:function(data, textstatus) {fn.success (data, textstatus); }, Beforesend:function(XHR) {fn.beforesend (XHR); }, Complete:function(XHR, ts) {fn.complete (XHR, TS);        }        }); //5. Pass the latest parameters back to the Ajax object_ajax (_options); };}) (jQuery);

If you have not contacted jquery inside $.extend This method of children's shoes may not understand what the above means. Well, let's start by looking at how the jquery API interprets the $.extend () method.

What do you mean? Let's see the official two examples.

Chestnut One:

var false, Limit:5, Name: "foo" }; var true, Name: "Bar" };$.extend (settings, options);

Results:

true, Limit:5, Name: "Bar"}

Chestnut II:

var empty = {}; var false, Limit:5, Name: "foo" }; var true, Name: "Bar" }; var settings = $.extend (empty, defaults, options);

Results:

true, Limit:5, Name: "Bar"true, Limit:5, Name: "Bar"}

The two simple examples above illustrate that the Extend () method works by merging another object, having the same overlay, and not adding the same one. It's that simple.

Understanding the role of $.extend (), we can probably read the above extension Jquery.ajax implementation of it. The main steps are divided into:

1) define the default error handling method.

var fn = {            function  (XMLHttpRequest, Textstatus, Errorthrown) {                True , timeout:0, Positionclass: ' Toast-top-full-width ' })            ,            function  (data, Textstatus) {},            function  (XHR) {},            function  (XHR, TS) {}        }

2) Determine whether the user has customized the error:function () {} when calling $.ajax ({}), and if so, use a user-defined, or default error-handling method.

3) use $.extend () to pass the error default processing method to the parameters of $.ajax (). We look at the options parameter with all the arguments in the $.ajax () method, and then expand it with the default FN.

Through the above three steps can be implemented to the $.ajax () method inside error default processing method. With this extension, we can still $.ajax ({}) to the extent that the user is completely not aware of the change, so that the AJAX request is sent, and if there is no special case, do not write the error handling method.

3, the meaning of component expansion

The use of component extensions can help us add some of the processing requirements that are relevant to our system's business on top of the existing components, while using the same as using native components, eliminating the need to encapsulate a layer of bloat on the component.

Second, expand their own components

The Error event handling method for $.ajax () is extended by the $.extend () method above. Let's try to encapsulate a component of our own, the function is simple, but the comparison is descriptive. Let's take the Select component as an example, in many cases, the option in our select needs to fetch data from the database, so the general practice is to send an AJAX request and then spell the HTML in the success method. Now let's encapsulate a select remote fetch data method.

1. Code implementation and usage examples

First on the dry, will write the whole out:

(function ($) {     //1. Define extension methods for jquery ComboBox$.fn.combobox =function(options, param) {if(typeofOptions = = ' String ') {            return$.fn.combobox.methods[options] ( This, param); }        //2. Merge the parameters passed in the call and the default parametersOptions = $.extend ({}, $.fn.combobox.defaults, Options | | {}); //3. Add default values        vartarget = $ ( This); Target.attr (' Valuefield ', Options.valuefield); Target.attr (' TextField ', Options.textfield);        Target.empty (); varOption = $ (' <option></option> ')); Option.attr (' Value ', ');        Option.text (Options.placeholder);        Target.append (option); //4. Determine whether the user passed the parameter list contains data data sets, if included, do not send Ajax from the background, or no Ajax from the background to fetch data        if(options.data) {init (target, options.data); }        Else {            //var param = {};Options.onBeforeLoad.call (target, Option.param); if(!options.url)return; $.getjson (Options.url, Option.param,function(data) {init (target, data);        }); }        functionInit (target, data) {$.each (data,function(I, item) {varOption = $ (' <option></option> ')); Option.attr (' Value ', Item[options.valuefield]);                Option.text (Item[options.textfield]);            Target.append (option);            });        Options.onLoadSuccess.call (target); } target.unbind ("Change"); Target.on ("Change",function(e) {if(Options.onchange)returnOptions.onchange (Target.val ());    }); }    //5. If a string is passed in, it represents the calling method. $.fn.combobox.methods ={getValue:function(JQ) {returnJq.val (); }, SetValue:function(JQ, param) {jq.val (param); }, Load:function(JQ, url) {$.getjson (URL,function(data) {jq.empty (); varOption = $ (' <option></option> ')); Option.attr (' Value ', '); Option.text (' Please select ');                Jq.append (option); $.each (data,function(I, item) {varOption = $ (' <option></option> ')); Option.attr (' Value ', item[jq.attr (' Valuefield ')]); Option.text (Item[jq.attr (' TextField ')]);                Jq.append (option);            });        });    }    }; //6. Default parameter list$.fn.combobox.defaults ={URL:NULL, param:NULL, Data:NULL, Valuefield:' Value ', TextField:' Text ', placeholder:' Please select ', Onbeforeload:function(param) {}, Onloadsuccess:function() {}, OnChange:function(value) {}};}) (jQuery);

Let's take a look at how our custom components work:

Usage One: Remotely fetching data from a URL and initializing it

First, define an empty select

<id= "Sel_search_plant"  class= "Form-control"></  Select>

and initialize it.

$ (function() {     $ (' #sel_search_plant '). ComboBox ({            '/apiaction/plant/ Find ',            ' tm_plant_id ',            ' Name_c '      );})

The parameters are simple and are not introduced. Very simple, there are wood ~ ~

Usage two: Values and settings
var strselectedvalue = $ (' #sel_search_plant '). ComboBox ("GetValue");
$ (' #sel_search_plant '). ComboBox ("SetValue", "AAA");

In fact, for the simple select tag, bloggers think the Getvalu and SetValue here is not very meaningful, because directly through the $ (' #sel_search_plant '). Val () can solve the matter, why should be lunar layer. Here is just a demonstration, imagine, if it is packaged into a similar select2 or multiselect this component, GetValue and setvalue the meaning of it, do you think?

2. Detailed explanation of the code

The implementation code above, if you can understand at a glance, prove that you are often the component of the shrimp, the following will not be seen. If you don't understand, it doesn't matter, we'll take the code apart and see what's inside.

(1) First look at the following wording that we see most often:

(function  ($) {      //....) Package component Logic }) (JQuery);

At the beginning to see this usage, Bo Master is also crazy grasping, this is what ghost, Sibuxiang ah. The use of a lot to know that this is the form of an anonymous function. Take it apart to see the following:

var function ($){       //..... Component Encapsulation Logic };FN (jQuery);

This means that a method is defined first and then called immediately, and jquery is equivalent to an argument. Open Jquery.js's original file to see that jquery is a global variable inside the file.

(2) The code that defines its own components:

function (options, param) {    };

It is customary to know that this means adding a custom method to a jquery object, such as the $ ("#id") that you want to start with the article. Myjscontrol ({}) , you can define $.FN as such . myjscontrol=function(options) {} .

(3) options = $.extend ({}, $.fn.combobox.defaults, Options | | {}); This sentence, see the above friends should still remember extend such a method, how, again to you. In fact, there is nothing to say, merging the default parameters and the parameters passed in by the user.

(4) Default parameter list

$.fn.combobox.defaults = {        null        , null,        null ,        ' Value ',        ' text ',        ' Please select ',        function  (param) {},         function  () { },         function (value) {}    };

If the user does not have a parameter, the default argument list is used. If you're careful, you'll find that there's a default parameter list in the JS file for other bootstrap components that bloggers have previously shared. We can find two of them:

Bootstrap Uploading components

Bootstrap table Component

Basically all of these usages. In this way, whether you can also seal a JS component ~ ~

Iii. Summary

The above is the master of the JS component extension and packaging usage of understanding and summary. Of course, it's a relatively simple package, and if you want to implement a bootstrap table-like component, it's a long way off. But the towering high-rise, as long as the foundation, to seal a table component of their own is not a big problem. If there is something wrong in the text, please note that the blogger would appreciate it. If this article can have the slightest help to you, trouble lift your small hand point a recommendation, Bo Master must continue to work hard, will better article share to everybody.

JS Component Series-Package your own JS components, you can!

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.