Search code examples
jsonfunctionvar

Use Variable from for function in another js file


i want to use a variable from an other js file but when i use the import and export statement that dont work because that say {file} is not defined. And my problem is my variable is in a function, and in a loop for. i think i'm doing it wrong but could you help me ?

here is the code on my fabric.js

    const initCanvas = () => (                                  
    new fabric.Canvas('canvas', {
        preserveObjectStacking:true,
        height: 450,
        width: 600,
        backgroundImage: {file}, <--- i want to use the variable "file" here 
        
    })
)  

and in my emil.js i have a function with this code

  DisplayCategory(category) {  
       (...)             //Function that generate te list of 
    else {                                          //Generate the product list of a category (ex : product[2][x])
        let product = [];
        let x = findProduct(product_array, selected_product);
        for (let y = 1; product_array[x][y]; y++) {
            var ext = ".jpg";
            var file = '/' + product_array[x][y] + ext; <--- file is defined here
            product.push(
                <Card style={{ width: '18rem' }} className={this.takeClass(product_array[x][y])} onClick={() => this.HandleOnClick(product_array[x][y], 2)}>
                    <Card.Img variant="top" src={file} /> <--- and is used here

The function is to long so i dont have put the rest


Solution

  • One common pattern is to have a common namespace, an object, written to window. That way your project writes only a single thing to the global namespace, and everything lives under there.

    This is an easy way to share data between scripts.

    Let's say we have bootstrap.js, which does this:

    window.someNamespace = {};
    

    Then in another script, you have this:

    someNamespace.sharedProperty = 'foo';
    alert('This script can call @sharedProperty -'+someNamespace.sharedProperty);
    

    Then in yet another script, you can read that property too:

    console.log(someNamespace.sharedProperty);
    

    ...because everything (or at least everything that needs to be shared - everything else should remain localised within closures) lives under window.someNamespace.