Search code examples
javascriptdrupaldrupal-7

Unexpected identifier when trying to include `attach: function` in a Drupal JavaScript file


I am new to Drupal and am following a tutorial to add some JQuery to a module's existing .js file.

Currently, the module's .js file looks kind of like this:

(function($, Drupal, google, window, document, undefined) {
  Drupal.behaviors.moduleName = {
   map: null,
   stores: [],
   markers: [],
   attach: function(context, settings) {
     //EXISTING FUNCTION THAT DOES SOMETHING
   }
}

All I want to do is add:

attach: function(context, settings) {
  console.log("Hello world");
};

as a proof of concept.

I've added this directory below the existing function, but when I refresh the page breaks and I get an error in my console:

Uncaught SyntaxError: Unexpected identifier

pointing to the line where I've added my function.

Would anyone know the correct way of doing this?


Solution

  • You have to close the first parentheses. Additionally, I think you are trying to write an IIFE (Immediately Invoked Function Expression), so if that is the case, you would need to call the function as well. Try this:

    (function($, Drupal, google, window, document, undefined) {
      Drupal.behaviors.moduleName = {
       map: null,
       stores: [],
       markers: [],
       attach: function(context, settings) {
         //EXISTING FUNCTION THAT DOES SOMETHING
       }
    })(); // I added a )(); here