Encapsulate your own JS component _ javascript skills

Source: Internet
Author: User
Tags toastr
This article mainly introduces how to encapsulate your own JS components, and how to understand and summarize js component extension and encapsulation usage. If you are interested, refer 1. Expand existing components
1. Background
Most of the time, we use jquery. ajax to send requests to the background, such

$. Ajax ({type: "post", url: "/User/Edit", data: {data: JSON. stringify (postdata)}, success: function (data, status) {if (status = "success") {toastr. success ('data submitted successfully'); $ ("# tb_aaa "). bootstrapTable ('refresh') ;}, error: function (e) {}, complete: function (){}});

This kind of code is too common. At this time, we have the requirement that we do not want to write the error: function (e) {} code every time when calling ajax requests, but we want it to output ajax error information to the browser every time so that users can see it. What should we do?

2. Implementation Principle
It is not difficult to achieve the above results. We can encapsulate $. ajax ({}) into a layer and define the event corresponding to the error in the encapsulated public method. Indeed, this can meet our requirements, but it is not perfect. The reason is very simple: 1) encapsulate another layer on the foundation of jquery, which is not efficient enough; 2) Change the caller's habits, every time ajax is called, we need to follow the rules of our defined method, instead of using the native $. ajax ({}), which we don't really want to see.

In this case, how can we achieve both the control encapsulation and the above requirements? The answer is to use our $. extend to extend the native jquery. ajax.

In fact, it is not difficult to implement it. The following code can meet our requirements.

(Function ($) {// 1. get $. ajax object var _ ajax =$. ajax; $. ajax = function (options) {// 2. the default error handling method var fn = {error: function (XMLHttpRequest, textStatus, errorThrown) {toastr is defined each time an ajax request is sent. 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 the error processing method is written during the call, 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. extended native $. ajax method, return the latest 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 never touched the $. extend method in jquery, you may not be able to understand what the above means. Well, let's first look at how jquery API explains the $. extend () method.

What does it mean? Let's look at the two official examples.

Chestnut 1:

var settings = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };$.extend(settings, options);

Result:

settings == { validate: true, limit: 5, name: "bar" }

Chestnut 2:

var empty = {};var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };var settings = $.extend(empty, defaults, options);

Result:

settings == { validate: true, limit: 5, name: "bar" }empty == { validate: true, limit: 5, name: "bar" }

The preceding two simple examples show that the extend () method is used to merge another object. If the same object exists, it overwrites the object. If not, it is added. That's simple.

After learning about the functions of $. extend (), we can probably understand the implementation of the extension jquery. ajax above. The main steps are as follows:

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'});}, success: function (data, textStatus) {}, beforeSend: function (XHR) {}, complete: function (XHR, TS ){}}

2) Determine whether the user is calling $. whether the error: function () {} is customized when ajax ({}) is used. If yes, the user-defined error is used. Otherwise, the default error processing method is used.

3) use $. extend () to pass the default error handling method to the $. ajax () parameter. We can see that the options parameter contains all the parameters in the $. ajax () method, and then extend it with the default fn.

The above three steps can be used to implement the default error handling method in the $. ajax () method. In this way, we do not feel any changes for our users. We can still send ajax requests using $. ajax ({}); in this way. If there are no special circumstances, we do not need to write an error processing method.

3. Significance of component Extension
Using component extension can help us add some processing requirements related to our system business to the original components. In use, it is called like using native components, this removes the hassle of encapsulating a layer of bloated components.

2. Expand your own components
The preceding Code uses the $. extend () method to extend the error event handling method of $. ajax. Next we will try to encapsulate a component of our own. The function is very simple, but it is descriptive. Let's take the select component as an example. In many cases, the options in the select statement need to retrieve data from the database. Therefore, the general method is to send an ajax request, then, splice html in the success method. Now we will encapsulate a remote data retrieval method for select.

1. Code implementation and use example
Let's get the goods done first and complete the written:

(Function ($) {// 1. define jquery Extension Method combobox $. fn. combobox = function (options, param) {if (typeof options = 'string') {return $. fn. combobox. methods [options] (this, param);} // 2. merge the parameters passed during the call with the default parameters options = $. extend ({}, $. fn. combobox. ults, options | {}); // 3. add the default value var target =$ (this); target. attr ('valuefield ', options. valueField); target. attr ('textfield ', options. textField); target. empty (); var option = $ (''); Option. attr ('value', ''); option. text (options. placeholder); target. append (option); // 4. determine whether the data dataset is included in the parameter list passed by the user. if the dataset is included, you do not need to send ajax to retrieve data from the backend. Otherwise, you cannot send ajax to retrieve data from the backend 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. 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 in, the method is called. $. 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. attr ('value', ''); option. text ('Please select'); jq. append (option); $. each (data, function (I, item) {var 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: 'select', onBeforeLoad: function (param) {}, onLoadSuccess: function () {}, onChange: function (value) {};}) (jQuery );

Let's take a look at how to use custom components:

Usage 1:Remotely retrieve and initialize data through URL
First, define an empty select

 

Then initialize it

$(function(){   $('#sel_search_plant').combobox({      url: '/apiaction/Plant/Find',      valueField: 'TM_PLANT_ID',      textField: 'NAME_C'   });})

The parameters are very simple. Easy to use ~~

Usage 2:Values and settings

var strSelectedValue = $('#sel_search_plant').combobox("getValue");$('#sel_search_plant').combobox("setValue", "aaa");

In fact, for simple select tags, the bloggers think that getValu and SetValue here are of little significance, because they directly use $ ('# sel_search_plant '). val () can solve the problem, it is necessary to seal another layer. Here is just a demonstration. Imagine that if it is encapsulated into a component similar to select2 or multiselect, the meaning of getValue and setValue will exist. What do you think?

2. Code details
The above implementation code, if you can understand it at a glance, proves that you often seal the components of prawns, the following does not need to be read. It doesn't matter if you don't understand it. Let's take the code apart and take a closer look at what's in it.

(1) first, let's take a look at the following statements:

(Function ($) {//... encapsulate component logic}) (jQuery );

At the beginning, I saw this kind of usage, and the bloggers were also crazy about it. What is this. It is known that this is the form of an anonymous function after it is used more often. Take it apart as follows:

Var fn = function ($) {//... component encapsulation logic}; fn (jQuery );

That is to say, this statement defines a method first and then immediately calls this method. jQuery is equivalent to a real parameter. Open the original file of jquery. js and you can see that jQuery is a global variable in this file.

(2) code for defining your own components:

$.fn.combobox = function (options, param) {  };

You should be familiar with this writing method. This indicates adding a custom method to the jquery object. For example, you want to use the $ ("# id") at the beginning of the article "). you can define $. fn. myJsControl = function (options ){}.

(3) options = $. extend ({}, $. fn. combobox. defaults, options | {}); those who have read the above should still remember the extend method. There is nothing to say about this sentence. Merge the default parameters with the parameters passed in by the user.

(4) default parameter list

$. Fn. combobox. defaults = {url: null, param: null, data: null, valueField: 'value', textField: 'text', placeholder: 'select', onBeforeLoad: function (param) {}, onLoadSuccess: function () {}, onChange: function (value ){}};

If no parameter is input, the default parameter list is used. If you are careful enough, you will find such a default parameter list in the js files of other bootstrap components shared by the blogger. Let's look for two items at will:

Bootstrap Upload Component

Bootstrap table component

This is basically the case. In this way, you can also create a js component by yourself ~~

The above is a summary of js component extension and encapsulation usage. I hope you will like it.

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.