Can I create a script include which is singleton ? I want this to be initialized only once ?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-08-2018 10:20 AM
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();
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-08-2018 06:43 PM
Small correction:
var SingletonScriptInclude = (function () {
/*
** Class Variables
*/
var grSingleInstance;
Did you mean to say Instance variables

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-08-2018 06:46 PM
yeah
ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-08-2018 06:50 PM
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);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-08-2018 07:13 PM
Out of curiosity.... what's the subscriber/publisher for?