javascript - output or use a js variable from the function (function ($, Drupal) {}) Drupal - Stack Overflow

admin2025-04-18  3

After sending data from my php to my js with DrupalSettings, I can use this data only in the function

(function ($, Drupal) {
    var myData = null; 
    Drupal.behaviors.customJs = {
        attach: function (context, settings) {
            if (settings.my_module && settings.my_module.myData) {
                myData = settings.my_module.myData; 
                if (myData.length > 0 && myData[0].back_file && myData[0].back_file.url) {
                    this.load.image("card-back", myData[0].back_file.url);
                }
            }
        }
    };
})(jQuery, Drupal);

I want to be able to use my myData variable outside because I use the phaser library and if I define a class in this function to use my variable, it becomes unfindable for my other files that use it For a concrete example I try to do this:

class Preloader extends Phaser.Scene {
  constructor() {
    super({
      key: 'Preloader'
    });
  }

  preload() {
    (function($, Drupal) {
      var myData = null;
      Drupal.behaviors.customJs = {
        attach: function(context, settings) {
          if (settings.my_module && settings.my_module.myData) {
            myData = settings.my_module.myData;
          }
        }
      };
    })(jQuery, Drupal);

    this.load.image("card-back", myData[0].back_file.url);
  }
  create() {
    this.scene.start("Play");
  }
}
转载请注明原文地址:http://anycun.com/QandA/1744911710a89370.html