Communication between scripts | Three methods

How to properly transfer data between two scenarios.

In this particular case, I have an element in one script, but I want to add it to another script.

The easiest way to do this is to use the global window object as an intermediate.

But globals are not the best practice.

What is the correct way to pass this element to another script?

Both scripts are encapsulated in a module template.

Script 0 Create an item point

var element = document.createElement( "div" );
element.innerHTML = response_text;

Script 1 Add an item point

Vi.sta = {

    // implemented in the boot loader - shared global space - appended child already - you don't have to append until now.
    // Static data has already been composed. 
    // Pull off window and append or best practice

};

Both are enclosed in a module template.

(function(){ 
    // the code here 
})()
+5
source share
3 answers

All JS scripts run in a global scope. When files are uploaded to the client, they are analyzed in a global area.

So, if you have

// File_1.js
var myObj = { colour : "blue" };

Nothing bothers you there:

// File_2.js
var otherObj = { colour : myObj.colour };

While File_1.js is loading before File_2.js

, : MYNAMESPACE = {};, ( " ", , ), .

, , interface .

SANDBOXING , proxy, service-locator "registry", messaging-system mediator-pattern.

+4
window.sharedSpace = {};
sharedSpace.sharedValue = 'foo bar';

, .

+5

?

var module1 = (function () {
    return {
        func1: function () {
            // get your element
            var someElement = ...;

            // pass it to the other module
            module2.func2(someElement);
        }
    };
}) ();

var module2 = (function () {
    return {
        func2: function (someElement) {
            // do whatever you want with someElement
        }
    };
}) ();
+1

All Articles