Implementation of React jquery Common component celling

Source: Internet
Author: User
Tags unique id

At present, the more popular react do have many advantages, such as virtual dom, one-way data flow state machine Idea. There is the idea of reusable components and so On. Coupled with JSX grammar and es6, to adapt to the development is indeed much faster, it is worth everyone to try. In fact, the idea of component has been raised, the original development will also draw some public modules Out. But the ideological impact brought by react is revolutionary, and it may not be appropriate to apply a phrase that might be inappropriate, to describe: all things are components, under the influence of this thought, no matter what the framework can draw some public modules out, should uphold a state of mind: any code should try not to repeat two times, If so, you can consider encapsulating them as Components. of course, not blindly advocating blind to pull away, this degree or to grasp the good.

But there is no one, not to mention Things. React although good, but the current domestic situation is still there is a very troublesome browser series-microsoft's ie Series. Although Microsoft's latest IE series is no longer so maverick, but users will not necessarily upgrade it. I can use a browser, why bother to upgrade at any time, and there is a minority of this IDEA. So the user-oriented system, according to our own statistics of the browser usage (handy Amway your own browser statistics tool https://github.com/future-team/cat-browser). IE6 the rank of the goods is not too far behind, not to mention ie7-9!

To be compatible with these maverick youth of literature and art, react really a little overwhelmed. Although there are some ways to solve some problems, such as the introduction of ES-SHIMS conversion ES6 syntax of the unprepared support Phenomenon. But overall, it's not going to Work. testimonials, the previous period of time a project using react to develop, requirements compatible with ie8, but react the hash value of the route in the IE8 will be lost .... In the end there are some other ways around. So there is a need for jquery.

If you develop two sets of components, the cost is quite large, and the duplication of work is not small. So there's an idea of whether a common component can be developed, and jquery and react technology stacks are available. At the beginning of the time also felt not very realistic, after all, the two technologies of the positioning and development model there is a big difference. But fantasy is no use, hands-on practice is the kingly. (there's a bit more in the preface today ...) So I'm going to implement a celling Component. the name is really bad, is to achieve a simple suction ceiling, suction bottom and the middle of the specific conditions of the ceiling of a positioning component.

First analyze the possibility of implementation:

first, Analyze the difference between the Two:

1, in the HTML rendering: jquery is just a class library, the specific DOM element or HTML to render or other way to insert, react through their own JSX syntax to put together through the virtual DOM to render

 2. How to operate the dom: jquery realizes the requirements by directly manipulating the real Dom , react each component as a state machine, needs to re-render its own virtual DOM by changing the state, and the diff algorithm decides to update to No

3, the event binding processing way different: jquery has its own set of event processing system, react is the Same. In general, both are different packages on the basis of native js.

In fact, The main difference is the view-related parts. But the logical part is the same as a component of the same function. This shows that our packages are fully achievable.

second, the current favourable technology:

Although ES6 has not yet been formally released, the existence of Babel has solved the Problem. ES6 proposed some new features and grammar sugar, a great deal of simplicity of some tedious wording. In particular, the addition of class and inheritance attributes has made Es6 's inheritance relatively elegant. (refer to the relevant es6)

third, the realization of ideas and design:

The original idea was to pull away from a public base class to store the public logic part, and the applicable class, jq, and react of the jquery class re inherit from the class, each implementing a ui-related Section. As shown (ignoring the details of the class diagram will not be drawn now):

    

But suddenly I remembered the react that I mentioned just now, everything is a component .... Since they are all components, they all inherit from the class componet provided by React. Because multiple inheritance is Unrealistic. So it felt a little dark at the Time. later, after the old driver reminds me, there is a pattern that seems to have been born to solve it, and that is the decorator Pattern.

About decorating the pattern Here's just two simple words, decorators let's make it possible to annotate and modify classes, attributes, and so on at design Time. Decorators uses the ES5 Object.defineProperty to achieve this feature. In short, the decorator handles the incoming object, adding some static or instance methods or properties to it. The injection is implemented in the class that needs to add attributes by means of @. The decorator mode can refer to http://www.cnblogs.com/whitewolf/p/details-of-ES7-JavaScript-Decorators.html for Details.

The current implementation has changed, and the react class inherits from the Component,jquery and does not inherit any base class. The same section is injected through the decorator pattern, as shown in:

Examples of decorator implementations are as Follows:

To inject a common method into a specific class:

Iv. Concrete Implementation:

After the basic idea has been made, the rest of the code is written:

1, options.js: Simple Configuration file, root Specifies the element to be implemented, position: Specifies the orientation of the Top,bottom,middle. classnames.js match different position, get different class. The code is as Follows:

      

Let options = {    root:',    position:' top '= {    top:' fix-top ',    bottom:' Fix-bottom ',    middle:' fix-top '};

2, about the public Minix extraction: because the implementation of the component is simply a simple positioning component, so the overall logic is not Much. The main addition of some example methods, to obtain different positioning of the class, to generate a unique key, etc., in order to unify the class, there is no way to apply the jq, but they encapsulated a number of methods, so react and jquery universal.

1Import options from './options.js ';2Import classnames from './classname.js ';3ExportdefaultObjs=>{4objs.prototype.test=function(){5Console.log (' test1 ');6     };7Objs.prototype.getcname=function(pos = ' top '){8         returnclassnames[pos];9     };Tenobjs.prototype.ismiddle=function(pos = ' top '){ one         returnpos = = ' middle '; a     }; -     /** - * Get a unique ID the      * */ -objs.prototype.getuniq=function(){ -         return' Cell ' +math.floor (math.random () *100); -     }; +     /** - * Is there a class +      * */ aObjs.prototype.hasClass =function(obj,cls) { at         returnObj.className.match (NewRegExp (' (\\s|^) ' +cls+ ' (\\s|$) ')); -     }; -  -     /** - * Add Classs -      * */ inObjs.prototype.addClass =function(obj,cls) { -         if(! this. Hasclass (obj, CLS)) { toObj.classname = (obj.classname + "" + cls). replace (/\s{2,}/g, ""); +         } -     }; the     /** * * Delete Class $      * */Panax NotoginsengObjs.prototype.removeClass =function(obj,cls) { -         if( this. Hasclass (OBJ,CLS)) { theLet Reg =NewRegExp (' (\\s|^) ' + cls + ' (\\s|$) '); +Obj.classname = Arguments[0].classname.replace (reg, "). split (" "). join (" "); a         } the     }; +     /** - * Take counter $ * @param bool $      * */ -Objs.prototype.getInvert =function(isbool) { -         return!isbool; the     }; -     /**Wuyi * Get the initial offsettop the * @param dom -      * */ wuObjs.prototype.getDTop =function(obj) { -         returnobj.offsettop; about     }; $}

3, the specific implementation of the class is relatively simple, through the @ injection minix, and then implement a specific method. Here take react as an example:

1 /**2 * React applicable3  * */4Import React, {proptypes,component} from ' React ';5Import reactdom from ' React/lib/reactdom ';6Import cellmin from './utils/cellmixin.js ';7Import '.. /css/cell-react.less ';8Import options from './utils/options.js ';9 @CellMinTen class Forreact extends component{ one constructor (props,context) { a Super (props,context); -          this. Uniquref = this. Getuniq (); -     } theStatic Defaultprops =options; - componentdidmount () { -          this. Ismiddle && this. addevent (); -     } + Render () { -         return( +<div ref={ this. uniquref} Classname={ a                  this. GetClass () at}> -{ this. props.children} -</div> -         ) -     } - getclass () { inLet pos = this. props.position; -          this. Ismiddle = this. Ismiddle (pos); to          this. CLS = this. Getcname (pos); +         return! this. ismiddle? this. Cls: '; -     } the     /** * * Monitor Scrolling events $      * */Panax Notoginseng addevent () { -Let Celldom = Reactdom.finddomnode ( this. refs[ this. uniquref]); the          this. Isreset =true; +Let Detop = this. Getdtop (celldom); aDocument.addeventlistener ("scroll", () ={ the           /** + * no longer listed -            * */ $         }) $     } - } -Module.exports = forreact;

here, the celling component for jquery and react is basically done. When introduced, you only need to introduce the required version separately.

To summarize, this kind of development does not really fit in at the Beginning. If you are skilled, you should have less effort than developing two sets of components for different frameworks. The potential pitfalls are that the components of this article are just simple examples of the logic and operations involved are not many, at present can be considered. But if the function is more complex components, whether it can also be a more thorough package extraction, it is debatable. Reference article http://www.cnblogs.com/whitewolf/p/details-of-ES7-JavaScript-Decorators.html

This article is still throwing bricks, hoping to get the opinion of the great God. Last Source Address https://github.com/future-team/multiple-celling

Original Address: http://www.cnblogs.com/pqjwyn/p/5813462.html

Implementation of React jquery Common component celling

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.