Loading module once, requirejs with examples
I already ask similar question: Requirejs, what it means "Requirejs loads
each module once"
but in that topic no one answer the main question, because i asked in
wrong way.
So i will provide some easy examples to show on what i mean:
Module counter.js
1: define([], function() {
2: console.log("Executing counter");
3: var counter = 0;
4:
5: return {
6: increment: function() { counter++; },
7: get: function() { return counter; }
8: };
9: });
Module test1.js
1: define(['counter'], function(counter) {
2: console.log("Executing test1");
3: counter.increment();
4: });
Module test2.js
1: define(['counter'], function(counter) {
2: console.log("Executing test2");
3: counter.increment();
4: });
Main.js
1: require(['test1', 'test2', 'counter'], function(test1, test2,
counter) {
2: console.log("Executing counter");
3: alert(counter.get());
4: });
So module main.js is entry point of the application which will first load
dependencies "test1", "test2" and "counter". (Executing order: Executing
counter, Executing test1, Executing test2, Executing main)
So if i understand sentence "Requirejs loads each module once" that means
(for example of counter.js) code from line 1 to 9 will be executed ONLY
ONCE beside fact that test1, test2 and main module have counter in their
dependencies list? If that is correct, test1 is "in charge" for executing
counter module? And if that is correct, after executing counter, in memory
will be ONLY ONE object which will be returned from counter? When test2
load counter it will get that ONE object? (in another words test2 will not
execute again code from counter neither main, they will use existing
counter object)? SO, am i creating SINGLETON here?
In the end all of the modules can affect counter value (in beginning,
counter = 0) through functions(increment, get) closures? Closures will be
alive while counter object exist in memory?
No comments:
Post a Comment