Requirejs, what it means “Requirejs loads each mod

2019-06-08 01:45发布

问题:

So if i have some module like:

//test1.js
define([], function() {
    var counter = 0;

    return {
        increment: function() { counter++ }
    };
});

Requirejs will load this module once(to be aware of local variables of this module) and never again? Variable counter will be alive through closure from returning object(through increment function)?

What about next example?

//test2.js
define([], function() {
    var value = 10;

    document.getElementById('asd').addEventListener('mousedown', function(e) {
        value = Math.random();
    });

    return value;
});

With this structure of code this event never get triggered because requirejs will load/execute this only once? Here exported value will be 10 and it cant be changed ever? So for this example i only have one solution and that is returning a function from this module(when i want effect like "execute this module more than once" speaking figuratively)?

So is this correct way to do it?

//test3.js
define([], function() {
    return function() {
        return Math.random();
    };
});

//test4.js
define(['test3'], function(test) {
   document.getElementById('asd').addEventListener('mousedown', function(e) {
        alert(test());
   });
});

Fell free to post any other pitfall which you find interesting about Requirejs.

回答1:

How about something like this:

define([], function() {
    var value = 10;

    document.getElementById('asd').addEventListener('mousedown', function(e) {
        value = Math.random();
    });

    return {
        getValue: function(){return value;}
    };

});

The variable value will retain its state internal to the define function but when its returned by define the result is passed by value (not by ref) which will never be updated.

Instead of doing this you can return a method which will get you the current value of your value when you call it. This means you can retrieve the updated value



回答2:

At the end its very easy to understand. All requireJs does, is to evaluate the passed function and return the same result to every module that requires it. So if you need the result from the last mousedown you have to return either an object holding the value, or a function that returns the value:

define([], function () {
  var result = {value:10};
  //the listener is bound when the module loads, maybe you should wrap this in domLoad listener as well   
  document.getElementById('asd').addEventListener('mousedown', function (e) {
    result.value = Math.random();
  });

  return result;
});

define(['test2'], function (test2) {
  var value = test2.value;
});

define([], function () {
  var result = {value:10};

  document.getElementById('asd').addEventListener('mousedown', function (e) {
    result.value = Math.random();
  });

  return result;
});

define(['test2'], function (test2) {
  var value = test2();
});