Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I have a custom views plugin. When the view is displayed, the javascript below gets loaded. Note the custom method, do_stuff, which gets called from within Drupal.behaviors.

(function ($) {
  $.fn.do_stuff(indx){
    alert (indx);
  }
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      if (settings.hasOwnProperty('mymodule')) {
        $('.my-item').each(function(indx, item) {
          // do stuff to each item
          $(this).do_stuff(indx);
        });
      }
    }
  } 
}(jQuery));

I would now like to create a second plugin, which loads a second javascript file. This second javascript file needs access to the custom method, do_stuff. Is there a way I could access the do_stuff code defined in the first javascript file, from within the second javascript file? For example, is there a way to move the custom method inside Drupal.behaviors, so that it could then be accessed from within any other javascript file?

share|improve this question

1 Answer

up vote 2 down vote accepted

I use a slightly different JS pattern with Drupal, which is based on the Javascript Module Pattern.

var FOO = (function(me, $, Drupal, undefined) {
  me.name = "FOO";

  function do_something_awesome () {
  }

  me.do_stuff = function do_stuff () {
  }

  function init (context, settings) {
    me.do_stuff();
    do_something_awesome();
  };

  Drupal.behaviors[me.name] = {
    attach: init
  };

  return me;
}(FOO || {}, jQuery, Drupal));

Anything directly attached to me will be public on the FOO. The rest is private. Typically, I will pass in FOO into the closure in dependent libraries.

share|improve this answer
One thing I do not understand: Why did you include 'undefined' as one of the input variables? – user606696 May 24 at 3:53
1  
@user606696 See stackoverflow.com/questions/9602901/… – MPD May 24 at 11:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.