0

Why can't I call my custom test() method?

Attempt 1

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

define([
 'jquery',
 'domReady!'
], function($) {
 function test()
 {
 alert("it works!");
 }
});

app/code/Company/Test/view/frontend/templates/forms/default.phtml

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

Output:

Uncaught ReferenceError: test is not defined

Attempt 2

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

define([
 'jquery',
 'domReady!'
], function($) {
 function test()
 {
 alert("it works!");
 }
});

app/code/Company/Test/view/frontend/templates/forms/default.phtml

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

Output:

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

Attempt 3

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

define([
 'jquery',
 'domReady!'
], function($) {
 return function test()
 {
 alert("it works!");
 }
});

app/code/Company/Test/view/frontend/templates/forms/default.phtml

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

Output:

contacts:2958 Uncaught TypeError: script.test is not a function
asked Nov 22, 2022 at 12:18

1 Answer 1

0

Figured it out:

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

function test()
{
 alert("it works!");
}

app/code/Company/Test/view/frontend/templates/forms/default.phtml

<script>
 require(['Company_Test/js/test'], function() {
 test();
 });
</script>
answered Nov 22, 2022 at 12:41

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.