Calling a function within jQuery from global scope

Viewed 20338

I've seen several issues about issues related to this, but none that provided a definite answer.

In this JavaScript:

function global_function() {
    a_jquery_function();
}

$(function () {
    var a_jquery_function = function () {
        do_something();
    };
});

Can I do something so that the global function can call the jQuery function? Obviously, it can't be done the way I do it there, but I was wondering if it could be done using jQuery.fn or using custom events. For example:

function global_function() {
    $.fn.a_jquery_function();
}

$(function () {
    $.fn.a_jquery_function() = function () {
        do_something();
    };
});

or

function global_function() {
    trigger_event('my_event', args);
}

$(function () {
    $(document).on('my_event', function(args) {
        do_something();
    });
});

I've tried the first one, but I ran into problems. If I know either is possible, I'll work on them more. But if someone out there knows that it's not possible to do this, I suppose I'll have to give it up.

Thanks.

4 Answers

you can write your global jQuery function like this

(function($){
  $.fn.func_name = function(var){
      write your code and functions here
  }
})(jQuery);

in your html or js file call $().func_name(var) to register.


Related