One, extend the existing components
1. Demand background
Many times, we use Jquery.ajax to send requests to the background, like
$.ajax ({
type: "Post",
URL: "/user/edit",
data: {data:JSON.stringify (PostData)},
success:function (data, status) {
if (status = = "Success") {
toastr.success (' Successful submission data ');
$ ("#tb_aaa"). Bootstraptable (' refresh ');
}
,
error:function (e) {
},
complete:function ( ) {
}
});
This kind of code is too common, this time we have such a demand: when we call the AJAX request, we do not want to write Error:function (e) {} Every time, but we want it each time the AJAX error messages to the browser to allow users to see. What do we do?
2. Principle of realization
In order to achieve the above effect is not difficult, we can encapsulate the $.ajax ({}) layer, in the encapsulated public methods to define the corresponding Error event. Indeed, this will meet our requirements, but not perfect, the reason is very simple: 1 on the basis of jquery to encapsulate a layer, inefficient; 2 need to change the habits of the caller, each time invoking Ajax needs to be written according to the rules of the method we defined, not directly with the native $.ajax ( {}) This type of writing, which we do not want to see.
So how do we do that without encapsulating the controls and achieving 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 code will be able to meet our requirements.
(function ($) {//1. $.ajax object var _ajax = $.ajax; $.ajax = function (options) {//2. Define default error handling each time a call is sent to an AJAX request var fn = {Error:function (XMLHttpRequest, Textstatus, Errorthrown) {toastr.error (xmlhttprequest.responsetext, ' error message ', {closebutton:true, timeout:0, posi
Tionclass: ' Toast-top-full-width '}); }, Success:function (data, textstatus) {}, Beforesend:function (XHR) {}, Complete:function (XHR, TS
{}}//3. If you write the error processing 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 native $.ajax method, return the most recent parameter 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. Return the latest parameters 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 meaning. OK, let's first look at how the jquery API interprets the $.extend () method.
What does that mean? Let's see the official two examples.
Chestnut One:
var settings = {validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
$.extend (settings, options);
Results:
Settings = = {Validate:true, limit:5, Name: "Bar"}
Chestnut Two:
var empty = {};
var defaults = {Validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
var settings = $.extend (empty, defaults, options);
Results:
Settings = = {Validate:true, limit:5, Name: "Bar"}
empty = = {Validate: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 adding without the same. It's so simple.
Understanding the role of $.extend (), we will be able to understand the above expansion of the implementation of the Jquery.ajax bar. The main steps are divided into:
1) define the default error handling method.
var fn = {
error:function (XMLHttpRequest, Textstatus, Errorthrown) {
Toastr.error ( Xmlhttprequest.responsetext, ' error message ', {closebutton:true, timeout:0, Positionclass: ' Toast-top-full-width '});
},< C7/>success:function (data, textstatus) {},
beforesend:function (XHR) {},
complete:function (XHR, TS) {}
}
2) to determine whether the user has customized Error:function () {} when calling $.ajax ({}), and if defined, uses the user-defined, otherwise the default error handling method.
3 use $.extend () to pass the error default processing method into the parameters of $.ajax (). When we look at the options parameter, we include all the parameters in the $.ajax () method, and then extend it with the default FN.
Through the above three steps can realize to $.ajax () method inside error default processing method. This extension, for our users completely does not feel the change, we can still $.ajax ({}), so to send the AJAX request, if there is no special circumstances, do not write error processing methods.
3, the significance of component expansion
The use of component extensions can help us add some of the processing requirements associated with our system business to the original component, while in use, as with native components, eliminating the need to encapsulate a layer of bloat on the component.
Second, expand their own components
The Error event handling method of $.ajax () is extended above through the $.extend () method. Let's try to encapsulate one of our own components, which is simple, but more descriptive. We take the Select component as an example, in many cases, the option in our select is to take data from the database, so the general approach is to send an AJAX request, and then in the success method to spell HTML. Now we'll encapsulate a select remote data-fetching method.
1. Code implementation and usage examples
first dry goods, will be written out of the whole:
(function ($) {//1. Extension methods for defining jquery ComboBox $.fn.combobox = function (options, param) {if (typeof options = ' str
ing ') {return $.fn.combobox.methods[options] (this, param); //2. The arguments and default parameters that are passed in the call merge options = $.extend ({}, $.fn.combobox.defaults, Options | |
{});
3. Add default value var target = $ (this);
Target.attr (' Valuefield ', Options.valuefield);
Target.attr (' TextField ', Options.textfield);
Target.empty ();
var option = $ (' <option></option> ');
Option.attr (' value ', ');
Option.text (Options.placeholder);
Target.append (option);
4. To determine whether the user passed the parameter list contains data data set, if included, do not send Ajax from the background to fetch, otherwise send Ajax from the background to fetch data if (options.data) {init (target, options.data);
else {//var param = {};
Options.onBeforeLoad.call (target, Options.param);
if (!options.url) return;
$.getjson (Options.url, Options.param, function (data) {init (target, data);
});
} function init (target, data) { $.each (data, function (I, item) {var option = $ (' <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) return Options.onchange (Target.val ());
});
//5. If the string is passed, it represents the calling method.
$.fn.combobox.methods = {Getvalue:function (JQ) {return jq.val ();
}, Setvalue:function (JQ, param) {jq.val (param);
}, Load:function (JQ, url) {$.getjson (URL, function (data) {jq.empty ();
var option = $ (' <option></option> ');
Option.attr (' value ', ');
Option.text (' please choose ');
Jq.append (option);
$.each (data, function (I, item) {var option = $ (' <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 ', TEXTF Ield: ' text ', placeholder: ' Please select ', onbeforeload:function (param) {}, Onloadsuccess:function () {}, Onch
Ange:function (value) {}};
}) (JQuery);
Let's take a look at how our custom components work:
Usage One: remotely fetching data through a URL and initializing it
first, define an empty select
<select id= "sel_search_plant" class= "Form-control" ></select>
and initialize it.
$ (function () {
$ (' #sel_search_plant '). ComboBox ({
URL: '/apiaction/plant/find ',
valuefield: ' Tm_plant_ ID ',
textField: ' Name_c '
})
The parameters are very simple, they are not introduced. It's simple, there's wood.
Usage Two: values and Settings
var strselectedvalue = $ (' #sel_search_plant '). ComboBox ("GetValue");
$ (' #sel_search_plant '). ComboBox ("SetValue", "AAA");
In fact, for a simple select tag, the blogger feels that the Getvalu and SetValue here are of little significance, as it is directly through the $ (' #sel_search_plant '). Val () can solve the matter, why to Feng Yi layer. Here is just a demo, imagine, if it is packaged into similar select2 or multiselect such components, the meaning of GetValue and SetValue, you think?
2, code detailed explanation
The above implementation code, if you can understand at a glance, prove that you are often the components of the prawn, the following will not be seen. If you don't understand, it doesn't matter, we'll take the code apart and see what the hell is inside.
(1) First look at the following wording that we most often see:
(function ($) {
//.... Encapsulation component Logic
}) (JQuery);
At the beginning of this use, the blogger is also crazy grasp, this is what ghosts, Sibuxiang ah. The use of a lot of it before we know that this is the form of an anonymous function. Take it apart and look as follows:
var fn = function ($) {
///..... Component encapsulation Logic
};
FN (jQuery);
That means that this notation means defining a method first and then calling the method immediately, and jquery is equivalent to the argument. Open Jquery.js's original file to see that jquery is a global variable in this file.
(2) code that defines its own component:
$.fn.combobox = function (options, param) {
};
As you should know, this means adding a custom method to the jquery object, such as The $ ("#id") that you want to start with the article. Myjscontrol ({}) This usage, you can define $.FN. Myjscontrol=function (Options) {}.
(3) options = $.extend ({}, $.fn.combobox.defaults, Options | | {}); This sentence, read the above friend should still remember extend such a method, how, again come to you. There's really nothing to say about that. Merges default parameters and user-passed parameters.
(4) 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) {}
};
If the user does not have a reference, the default argument list is used. If you are careful, you will find that there is a list of default parameters in the JS file of other bootstrap components that the blogger shared before. Let's just look for two:
Bootstrap Upload Component
Bootstrap table Component
Basically all of these usages. In this way, whether you can also seal a JS component ~ ~
The above is the JS component expansion and encapsulation usage of the understanding and summary, I hope you like.