0

I have two files - main, and events. I'm trying to call some function from one file to another.

So, this is how it looks:

events

require(['app/main'], function(call) {
    // click event respond test
    document.body.addEventListener("click", function(e) {
        var target = e.target;
        if (target.hasClass === "call"){
            functionCall()();
        }
    });
});

main

define(["jquery"], function() {

    // Call
    var box = $('.box');
    return function functionCall(){
        box.addClass('visible');
    }
});

What is wrong, can anyboyd help?

2
  • I know you're trying to require a module in another file but what exactly are you trying to achieve when you call it? Commented Jan 24, 2014 at 16:00
  • call function from other file after click on some element - simple Commented Jan 24, 2014 at 16:02

4 Answers 4

4

main:

define(["jquery"], function($) {

    var main =  {
        functionCall: function(){
            $('.box').addClass('visible');
        }
    }

    return main;
});

events:

require(['jquery','app/main'], function($, main) {

    $('body').on('click', function () {
        if($(this).hasClass('call')){
            main.functionCall();
        }
    });

});
Sign up to request clarification or add additional context in comments.

Comments

0

One way is to add this code where you need to make call to function: require('pathToModuleOrModuleName').functionYouWantToCall()

But if you have module defined or required in the beggining (as 'main' in the events), then in place where call to function needed just add:

call.functionName();

Comments

0

Unless my eyes deceive me the simplest change to make to your code would be to replace this:

functionCall()();

with this:

call();

since the function that the main module returns is imported as call in your events module, because that's how you name it in the callback passed to define.

Comments

0

Firstly your code has some basic problems

In the following code

define(["jquery"], function() {

Where are you referring the query inside the function definition. I think you should first map the jquery defined into the function declaration like below

  define(["jquery"], function($) {

Secondly, what is the () doing after the calling function?

if (target.hasClass === "call"){
   functionCall()();
}

Remove the trailing () from that call. It should just be functionCall();

1 Comment

i have maped jquery in my main/config file, and that is the write mistake, my function is defined corectly... :)

Your Answer

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.