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')
asked Nov 22, 2022 at 13:53

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>
answered Nov 23, 2022 at 14:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.