Requirejs,它意味着什么“Requirejs加载每个模块一次” [英] Requirejs, what it means "Requirejs loads each module once"

查看:111
本文介绍了Requirejs,它意味着什么“Requirejs加载每个模块一次”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果我有一些类似的模块:

So if i have some module like:

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

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

Requirejs将加载此模块一次(以了解此模块的局部变量)并且再也不会?变量计数器将通过返回对象的闭包(通过增量函数)活着吗?

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;
});

使用这种代码结构,这个事件永远不会被触发,因为requirejs只会加载/执行一次这个?这里的出口值是10,它不能改变吗?
所以对于这个例子我只有一个解决方案,并且从这个模块返回一个函数(当我希望效果像执行这个模块不止一次时,比喻说)?

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)?

这是正确的方法吗?

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

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

可以免费发布任何有关Requirejs的其他陷阱。

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

推荐答案

这样的事情怎么样:

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

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

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

});

变量值将保留其在define函数内部的状态,但是当它返回时通过定义结果是通过值(而不是ref)传递,永远不会更新。

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

这篇关于Requirejs,它意味着什么“Requirejs加载每个模块一次”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆