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

I need to add my own little if's and checks in 3 functions inside

misc/ajax.js (
  Drupal.ajax.prototype.beforeSend,
  Drupal.ajax.prototype.success,
  Drupal.ajax.prototype.error
)

How can I override them in my module? I can't find a manual and it's not in Examples for Developers. Sorry if it seems a dumb question, but I'm a php developer - I can work with js, but I'm not so fluent with it.

  • Can I simply write it in my module's js file?
  • If 2 or 3 modules needs to modify them, how to avoid conflicts?
share|improve this question

1 Answer

up vote 1 down vote accepted

Drupal.ajax.prototype.beforeSend and the others are just variables that happen to have functions assigned to them. As long as your code appears in the page build after the original function implementations, you you should be able to just override what's already there:

(function($) {
  // In mymodule.js, which appears after ajax.js in the page build
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    // Replacement code.
  }
})(jQuery);
share|improve this answer
So, I'm doing it the right way, but that leaves my doubt - each module must take care to be the last one updating them on the page that needs it's changes, right? No way to prevent accidental modifications by others? – Mołot May 14 at 14:09
1  
Correct, this practice is usually referred to as 'monkey patching' and it's not an exact science unfortunately – Clive May 14 at 14:10
Oh. I was so sure there is some clean, safe, clever way I just cannot find due to my lack of js skill... I wouldn't asked if I knew. But I think I'll leave this question for future users looking for that nonexistent safe way. – Mołot May 14 at 14:12
Using other frameworks (Require.js, AngularJS, anything else that tries to bring Dependency Injection to Javascript) there are more satisfying ways of achieving the same results, but with plain 'ol JS/jQuery not so much. Your method is the best that I know of on top of Drupal – Clive May 14 at 14:16

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.