Home > Web Front-end > JS Tutorial > Implementation method of JS chain call_javascript skills

Implementation method of JS chain call_javascript skills

WBOY
Release: 2016-05-16 17:40:51
Original
1304 people have browsed it

Chain call
Chain call is actually just a grammatical trick. It allows you to express complex operations in a small amount of code by reusing an initial operation. The technology consists of two parts:

A factory that creates objects representing HTML elements.

A batch of methods that perform certain operations on this HTML element.

The structure of the call chain
The $ function is responsible for creating objects that support chain calls

Copy code The code is as follows:

(function() {
/*
* Create a private class
* @param {Object} els arguments A class array composed of all parameters
*/
function _$(els) {
this.elements = []; // Store HTML element
for(var i=0, len=els.length; i var element = els[i];
if(typeof element === 'string' ) {
                 element = document.getElementById(element);                                                         Actions that HTML elements can perform
_$.prototype = {
each: function() {},
setStyle: function() {},
show: function() {},
addEvent: function() {},
}; );



Since all objects will inherit the properties and methods of their prototype object, we can make those methods defined in the prototype object return a reference to the instance object used to call the method, so that those methods can be called in a chain .





Copy code
The code is as follows:


(function() {
/*
* Create a private class
* @param {Object} els arguments A class array composed of all parameters
*/
function _$(els) {
//...
}
//Operations that can be performed on HTML elements
_$.prototype = {
each: function(fn) { / /fn callback function
for(var i=0; i //Execute len times, each time passing an element elements[i] as a parameter
fn.call(this, this.elements[i]);
           }
                  return this; el) {
           el.style[prop] = value;
                                                                                                            var that = this;
this.each(function(el) {
that.setStyle('display', 'block');
});
return this;
},
addEvent: function (type, fn) {
var addHandle = function(el) {
if(document.addEventListener) {
el.addEventListener(type, fn, false);
            }else if(document. attachEvent) {
el.attachEvent('on' type, fn);
}
};
this.each(function(el) {
                  addHandle(el);
});
                       return this; 🎜> }

})();

//--------------------- test --------
$(window).addEvent('load' , function() {
$('test-1', 'test-2').show()
.setStyle('color', 'red')
.addEvent('click', function() {
          $(this).setStyle('color', 'green');
      });
})



Getting data using chained calling methods Use callback functions to get data from methods that support chained calling. Chained calls are great for assigner methods, but for getter methods, you may want them to return the data you want instead of this (the object on which the method is called). Solution: Use callback technology to return the data you want.





Copy code


The code is as follows:


window.API = window.API || function() {
var name = 'mackxu';
//Privileged method
this.setName = function(name0) {
name = name0;
return this;
};
this.getName = function(callback) {
callback.call(this, name);
return this;
} ;
};
//------------- test ---
var obj = new API();
obj.getName(console.log) .setName('zhangsan').getName(console.log);

Design a JS library that supports method chain calling
JS library features:

Events: Add and delete event listeners, and plan event objects

DOM: Class name management, style management

Ajax: Normalize XMLHttpRequest

Copy code The code is as follows:

Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
return this;
};
(function() {
function _$(els) {
//...
}
/*
* Events
* addEvent
* removeEvent
*/
_$.method('addEvent', function(type, fn) {
 > *RemoveClass
*Hover
*Hasclass
*getClass
*getstyle
*setstyle
*/
.method ('addclass' e) {            //...
                            .method('removeClass', function(classname)                                                  
                                                                                                                                              .
                                                                                                                                 . ) {
//...
})
/*
* AJAX
* * ajax
*/
.method('ajax', function(url, method ) {
          //...
                     ); /Resolve the JS library naming conflict problem
window.installHelper = function(scope, interface) {
scope[interface] = function() {
return _$(arguments)
}
}
})();



Summary:

Chained calls help simplify code writing and to some extent make the code more concise and readable. In many cases, using chained calls can avoid reusing an object variable multiple times, thereby reducing the amount of code. If you want to keep the interface of the class consistent and make both the assignor and the valuer support chain calls, then you can use a callback function in the valuer to solve the problem of obtaining data.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template