The previous article was to use the entire jquery library as a module. This article is to write a module of its own: selector.
For the demonstration, it is convenient to implement only three selector id,classname,attribute commonly used here. Requirejs uses define to define the module.
The new directory structure is as follows
This time a new subdirectory JS, put Main.js and selctor.js into which, Require.js still and index.html in the same level directory.
HTML as follows
<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "UTF-8"> <title></title> <styletype= "Text/css">#wrapper{width:200px;Height:200px;background:Gray; } </style></Head><Body> <DivID= "wrapper"></Div> <ScriptData-main= "Js/main"src= "Require.js"></Script></Body></HTML>
This time the script tag is placed behind the Div, because the selector is used to get the page DOM element, which waits until the DOM is ready.
Because put Main.js in the JS directory, here the value of Data-main should be changed to "Js/main".
Selector.js as follows
Definefunction(){ functionQuery (selector) {vars =Selector, Doc=document, Regid=/^#[\w\-]+/, Regcls=/^ ([\w\-]+)? \. ([\w\-]+)/, Regtag=/^ ([\w\*]+) $/, Regnodeattr=/^ ([\w\-]+)? \[([\w]+) (= (\w+))? \]/;//var context =//context = = undefined?//Document://typeof context = = ' string '?//Doc.getelementbyid (Context.substr (1,context.length))://context; if(Regid.test (s)) {returnDoc.getelementbyid (S.SUBSTR (1, s.length)); } } returnquery;});
The Define parameter is an anonymous function that returns Query,query as the function type after the anonymous function executes. Query is the implementation function of the selector.
Main.js as follows
require.config ({ baseUrl:' js '}); require ([' selector '],function(query) { var els = query (' #wrapper '); Console.log (ELS);})
The Require.config method executes the root directory of the module file configured with BaseURL as "JS", BaseURL, which can be either an absolute path or a relative path. The relative path is used here. Relative path refers to the page that introduces Require.js as the reference point, here is index.html.
Place the directory R2 on Apache or another Web server and access the index.html.
Network requests are as follows
Both Main.js and Selector.js were asked to come down.
Selector.js after downloading, use query to get the element with the page ID "#wrapper" and the console outputs the element. As follows
Summarize:
- Using BaseURL to configure the module root, BaseURL can be either an absolute or a relative path
- Use define to define a function type module, Requirejs module can be JS object, function or any other type (Commonjs/seajs can only be JS object)
Requirejs Introduction (II)