尝试在 Drupal JavaScript 文件中包含“attach: function”时出现意外标识符

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

我是 Drupal 的新手,正在按照教程将一些 JQuery 添加到模块的现有 .js 文件中。

目前,模块的 .js 文件看起来像这样:

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

我只想添加:

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

作为概念证明。

我已将此目录添加到现有功能下方,但当我刷新分页符时,我的控制台出现错误:

Uncaught SyntaxError: Unexpected identifier

指向我添加函数的行。

有人知道正确的做法吗?

您必须关闭第一个括号。此外,我认为您正在尝试编写 IIFE(立即调用的函数表达式),因此如果是这种情况,您还需要调用该函数。试试这个:

(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