Requirejs Introduction (III)

Source: Internet
Author: User

Requirejs Introduction (III)

This article is to write an event module that has a dependency. Event provides three methods of bind, unbind, trigger to manage DOM element events.

The event relies on the cache module and the cache module is similar to the $.data method of jquery. Provides methods for managing data stored on DOM elements, such as set, get, remove, and so on.

Example implementation: Add a Click event to all the paragraph P elements on the page, and the response function will pop up the P element's innerHTML.

The directories created are as follows

In order to get the elements, I used the selector.js of the previous writing. Not sticking its code.

Index.html as follows

1234567891011121314151617 <!doctype html>            <title>requirejs入门(三)</title>        <meta charset="utf-8">        <style type="text/css">            p {                width: 200px;                background: gray;            }        </style>        <body>        <p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p>        <script data-main="js/main"src="require.js"></script>    </body>

Cache.js as follows

123456789101112131415161718192021222324252627 define(function() {    varidSeed = 0,        cache = {},        id = ‘_ guid _‘;    // @private    functionguid(el) {        returnel[id] || (el[id] = ++idSeed);    }    return{        set: function(el, key, val) {            if(!el) {                thrownewError(‘setting failed, invalid element‘);            }            varid = guid(el),                c = cache[id] || (cache[id] = {});            if(key) c[key] = val;             returnc;        },        // 略去...    };});

The cache module has no special wording, unlike selector, which returns a JS object.

Event.js as follows

1234567891011121314151617181920 define([‘cache‘], function(cache) {    vardoc = window.document,        w3c = !!doc.addEventListener,        expando = ‘snandy‘ + (‘‘+Math.random()).replace(/\D/g, ‘‘),        triggered,        addListener = w3c ?            function(el, type, fn) { el.addEventListener(type, fn, false); } :            function(el, type, fn) { el.attachEvent(‘on‘+ type, fn); },        removeListener = w3c ?            function(el, type, fn) { el.removeEventListener(type, fn, false); } :            function(el, type, fn) { el.detachEvent(‘on‘+ type, fn); };    // 略去...        return{        bind : bind,        unbind : unbind,        trigger : trigger    };});

  

The event relies on the cache, and the first parameter array is placed in "cache" when defined. The second parameter is the function type, and its parameter is the Cache module object.
With this definition, when the Require event module is set, Requirejs automatically downloads the cache.js that is dependent on event.

Main.js as follows

123456789101112 require.config({    baseUrl: ‘js‘});require([‘selector‘‘event‘], function($, E) {    varels = $(‘p‘);    for(vari=0; i<els.length; i++) {        E.bind(els[i], ‘click‘function() {            alert(this.innerHTML);        });    }});

  

The root of the next module is still configured JS, and then use require to get the selector and the event module.
The callback function uses the selector $ (alias) and the Event management Object E (alias) to add a click event to all P elements on the page.
Note: The module name in the first parameter array of the require must correspond to the parameter one by one of the callback function.

Place the directory R3 on Apache or another Web server and access the index.html. Network requests are as follows

We saw that when Selector.js and event.js downloaded, event.js dependent cache.js was automatically downloaded. When you click on each P element on the page, the corresponding innerHTML will pop up. As follows

Summarize:
When a module relies on (a) on another module (b), the first parameter when defining the module is an array, and the module name (string type) in the array is the module on which it depends.
When there are multiple dependent modes, be aware that the parameter order of the callback function corresponds to the array element one by one. At this point Requirejs will automatically identify the dependencies and download them all before making callbacks.

Requirejs Introduction (III)

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.