0

Situation

The method "test" does exist two times. If I call it while both scripts are required, then only the last one is getting called e.g. the one from test2.js

app/code/Company/Test/view/frontend/web/js/test1.js

function test() { alert("test 1"); }
function foo() { alert("foo"); }

app/code/Company/Test/view/frontend/web/js/test2.js

function test() { alert("test 2"); }
function bar() { alert("bar"); }

app/code/Company/Test/view/frontend/templates/test.phtml

<script>
    require(['Company_Test/js/test1', 'Company_Test/js/test2'], function() {
        test();
        foo();
        bar();
    });
</script>

Output:

test2
foo
bar

Is there a way to only call the test method of test1.js without having to change the order of the dependencies?

I tried this:

app/code/Company/Test/view/frontend/templates/test.phtml

<script>
    require(['Company_Test/js/test1', 'Company_Test/js/test2'], function(test1, test2) {
        test1.test();
        foo();
        bar();
    });
</script>

But I get:

contacts:2964 Uncaught TypeError: Cannot read properties of undefined (reading 'test')

1 Answer 1

3

Your js files should be decorated as AMD module, basically wrap them in a define function:

app/code/Company/Test/view/frontend/web/js/test1.js

define(function () {
    return {
        test: function () {
            alert('test 1')
        },
        foo: function () {
            alert('foo')
        }
    }
});

app/code/Company/Test/view/frontend/web/js/test2.js

define(function () {
    return {
        test: function () {
            alert('test 2')
        },
        bar: function () {
            alert('bar')
        }
    }
});

Now your modules can be used correctly and you can call every function you defined like this:

app/code/Company/Test/view/frontend/templates/test.phtml

<script>
    require(['Company_Test/js/test1', 'Company_Test/js/test2'], function(test1, test2) {
        test1.test();
        test1.foo();
        test2.bar();
    });
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.