How import utility method in client script


  • GNU/Linux

    I create a new utils.js file in lib, and in this file I use this code:

    
    var Utils = {};
    
    
    Utils.getTipoBookmarked = function(oggettoBookmarked, tipoBookmarked) {
    	
    	...
    };
    Utils.checkIsChecked = function(selezionatiBookmarked, bookmarked) {
    	....
    };
    
    module.exports = Utils;
    

    Now I need to use these methods in a static/lib/add.js. (client file). This client file is something like this:

    'use strict';
    
    
    (function() {
    
    	$(document).on('click', '#buttonV', function() {
    //here I use the method in utils.js
    //The parameter is not a problem The problem is that utils is not defined
    var d=utils.getTipoBookmarked(param1,params2);
    });
    }());
    

    My problem is that the utils.js is not define. How I can import this?Anyone can help me?


  • Community Rep

    Assuming they are utility functions and not calling any server modules, you can wrap it in an IIFE and include it in your scripts in plugin.json. Checking the environment before exporting.

    (function () {
      var Utils = {};
    
      Utils.getTipoBookmarked = function(oggettoBookmarked, tipoBookmarked) {
    	
    	...
      };
      Utils.checkIsChecked = function(selezionatiBookmarked, bookmarked) {
    	....
      };
    
      if (typeof module === 'object' && module.exports) {
        module.exports = Utils;
      } else {
        window.myutils = Utils; // Edited
      }
    }());
    

  • Admin

    @yariplus said in How import utility method in client script:

    window.utils = Utils;

    Watch out for this, it would overwrite the utils object from nodebb.


  • Community Rep

    @baris Ah, nice.

    @Doppy Best to name it something like myutils, or prefixed with the name of your plugin.


Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.