Home > Article > Web Front-end > How to write a js/jQuery library (summary of experience)
Writingjs/jQueryThe plug-in has some conventional routines. According to these routines, there will be no big problems in the structure of the code. It is especially recommended. This project called javascript-patterns , I learned a lot from some demos.
Basic structure
Ordinary library
Just use the most basic anonymous function
(function(){ var root = this; root.YOURLIB = function(){ FUNC1 : function(){}, FUNC2 : function(){} } }())
You can also use call instead of closure. In this case, the two writing methods are equivalent. Undersocre.js uses the call writing method
(function(){ var root = this; root.YOURLIB = function(){ FUNC1 : function(){}, FUNC2 : function(){} } }.call(this))
jQuery plug-in
The following method can be used to make the plug-in cross CMD/AMD/Browser
(function (factory) { if (typeof define === 'function' && define.amd) { // AMD define(['jquery'], factory); } else if (typeof exports === 'object') { // CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { $.fn.render = function() {} $.render2 = function() {} }))
Of course, if Seajs and RequireJS are not considered, the most convenient way is to use anonymous functions and then use window.jQuery as a parameter Pass it in
Internal organization
We use these two projectsbootstrap-select v1.6.3,smooth-scroll Analyze,
Initialize
Generally, Libraries will provide a set of defaults configuration files, and then extend and smooth-scroll with user-defined settings when using them. The kind of
settings = extend(defaults, options ||{})); 写法就相当赞,可以以一种十分简单的方式防止空指针异常。
The rest is the funciton of dividing the business according to the business. As for how to divide, the only thing is to practice more.
In addition, it is a good habit to distinguish between external interfaces and internal interfaces by writing private and public in comments.
i18n and configuration management
i18n, right? Put all the international characters in defautls. The more elegant way is to define an object in defaults, so that the internationalization file
can be separated from the original library file. For details, refer to bootstrap-datapicker
THE END
The above is the detailed content of How to write a js/jQuery library (summary of experience). For more information, please follow other related articles on the PHP Chinese website!