简体   繁体   中英

How can I use a javascript function globally in Drupal 7

How can I use a javascript function globally in Drupal 7.

I have my javascript file set up like this and add it using drupal_add_js():

(function($) {
  function add_if_country_is_not_usa() {
   // Check what country it is

   // Update text, image, etc.. of a block.
  }
});

In my block WYSIWIG I added the following code (The reason I add it in the WYSIWIG is because I want it to update before the page is fully rendered):

<script type="text/javascript">
  add_if_country_is_not_usa();
</script>

But I get the following error: Uncaught ReferenceError: add_if_country_is_not_usa is not defined (anonymous function)

I read about adding functions to Drupal behaviors but that happens on document ready. I want to run the function as soon as the block is shown.

Any ideas?

Either define in the global scope, or do like below:

(function($) {
  function add_if_country_is_not_usa() {
   // Check what country it is

   // Update text, image, etc.. of a block.
  }

  // set as a property of the global object `window`
  window.add_if_country_is_not_usa = add_if_country_is_not_usa;
});

Not sure if this is the best way but I ended up being able to get it work using a namespaces. I call myGlobalObject.add_if_country_is_not_usa() from my block and it works now.

var myGlobalObject = mySingleGlobalObject || { 'country': {} };

(function ($) {
   myGlobalObject.country = '';

   myGlobalObject.add_if_country_is_not_usa = function() {      
     // Check what country it is

     // myGlobalObject.country = 'US';
   }
})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM