2

I have function bar which I need to call. I'm new to using callbacks, from what I understand the callback is still inside the scope of the ajax so it can't see bar. Is it possible to call bar on ajax success? bar is defined in module top.

define(["top"], function() {
    function foo(callback) {
        $.ajax({
            type: "GET",
            cache: false,
            dataType: 'json',
            url: "http://asdf/qwer",
            success: function(response) {
                callback(response);
            }
        });
    }
    foo(function(response) {
        bar(response);      
    });
});
2
  • Which module loader do you use (the "define" function)? The availability of bar depends on it and the code of the top module. Commented Jul 4, 2012 at 10:20
  • How is bar defined in the top module. Is it an object with a property .bar? Commented Jul 4, 2012 at 10:21

1 Answer 1

2

Assuming your top.js looks similar to this:

define( function() {
  return {
    'bar': function( data ){
             // some code here
           }
  };
} );

(Note that the function has to be exported/returned here!)

You can access the bar() function like this:

define(["top"], function( top ) {
    function foo(callback) {
        $.ajax({
            type: "GET",
            cache: false,
            dataType: 'json',
            url: "http://asdf/qwer",
            success: function(response) {
                callback(response);
            }
        });
    }
    foo(function(response) {
        top.bar(response);      
    });
});

See the require.js doc on working with dependencies inside a define() function.

You should add a parameter to the function inside define() for every required module. In the example case this is the top parameter. Afterwards you can call all exported properties of the requirement module by using this parameter.

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

1 Comment

There is 2-3 redundant functions here though. You just need success: top.bar if it's only used once. If there is multiple ones you just need success: callback and foo(top.bar)

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.