Can I create a script include which is singleton ? I want this to be initialized only once ?

rajeevnadgauda
ServiceNow Employee
ServiceNow Employee

This is what I have written in the script include 

The problem is I need the same ServerPubSub instance every time I refer it either in the Business Rule or other script includes. Is that possible currently it is initializing the whole script again when I use it at two places.

 

var ServerPubSub = function () {
    this.events = {};

    this.on = function (eventName, fn) {
        var self = this;



        self.events[eventName] = self.events[eventName] || [];
        gs.log(JSON.stringify(self.events) + " ---> ON REGISTERED 1" + fn);
        self.events[eventName].push(fn);
        gs.log(JSON.stringify(self.events) + " ---> ON REGISTERED");
    }
    this.off = function (eventName, fn) {
        var self = this;
        if (self.events[eventName]) {
            for (var i = 0; i < self.events[eventName].length; i++) {
                if (self.events[eventName][i] === fn) {
                    self.events[eventName].splice(i, 1);
                    break;
                }
            }
        }
    }
    this.emit = function (eventName, data) {
        var self = this;
        gs.log("Emitting ..... " + eventName + " -----> " + JSON.stringify(data));
        var self = this;
        if (self.events[eventName]) {
            self.events[eventName].forEach(function (fn) {
                fn(data);
            });
        }
        gs.log(JSON.stringify(self.events) + " ---> ON EMIT");
    }
}
ServerPubSub.prototype = {
    initialize: function () {
    },
    type: 'ServerPubSub'
};

ServerPubSub.instance = new ServerPubSub();
8 REPLIES 8

Small correction:

var SingletonScriptInclude = (function () {
	
	/*
    ** Class Variables
    */
	
    var grSingleInstance;

 

Did you mean to say Instance variables

yeah


ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

Javier Arroyo
Kilo Guru
I might not have gotten everything

ServerPubSub (function (params) {
    var events = {};

    function doOn(eventName, fn) {

        events.hasOwnProperty(eventName) ? events.push(fn) : events[eventName] = [fn];

    }


    function doOff(eventName, fn) {

        if (events.hasOwnProperty(eventName)) {
            for (var i = 0; i < events[eventName].length; i++) {
                if (events[eventName][i] === fn) {
                    events[eventName].splice(i, 1);
                    break;

                }
            }
        }
    }

    function doEmit(eventName, data) {
        if (events.hasOwnProperty(eventName)) {
            events[eventName].forEach(function (fn) {
                fn(data);

            });
        }


    }

    var publicAPI = {
        on: doOn,
        off: doOff,
        emit: doEmit

    }
    

    return publicAPI;

})(arguments);

Javier Arroyo
Kilo Guru

Out of curiosity.... what's the subscriber/publisher for?