Requirejs, what it means “Requirejs loads each module once”

ⅰ亾dé卋堺 提交于 2019-12-06 16:03:17

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

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();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!