- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
NOTE: MY POSTINGS REFLECT MY OWN VIEWS AND DO NOT NECESSARILY REPRESENT THE VIEWS OF MY EMPLOYER, ACCENTURE.
DIFFICULTY LEVEL: ADVANCED
Assumes good intermediate level knowledge and/or familiarity of Scripting in ServiceNow.
____________________________________________________________________________
I get this question a lot: "Hey Steve, I learned in the ServiceNow Scripting Fundamentals class that there are three different types of Script Includes, but I see other types that aren't described. How many different types of Script Includes are there?"
Wow. Several more than three that is for sure.
So, the ones I will cover are the ones I have dealt with (there are probably one or two I missed).
The types covered in this article:
1. Prototype class Script Include.
2. Function Script Include
3. Single Function Script Include
4. Abstract Script Include
5. Extends Script Include
6. External Library Port Script Include
7. ServiceNow Object Extension Script Include
8. Polyfill Script Include
1. Prototype class Script Include
This is the most common of the Script Include types. A prototype extends the platform definition by grafting in the functionality specified in the Script Include.
This type of Script Include requires "new-ing" to use and has an optional initialize function.
Usage:
var utils = new CIUtils();
var servicesAffected = utils.servicesAffectedByCI(...)
Definition:
var CIUtils = Class.create();
CIUtils.prototype = {
initialize : function() {},
servicesAffectedByCI: function(id, customValues) {...},
type: 'CIUtils'
};
2. Function Script Include
This type of Script Include is commonly used for utility libraries.
The type of script requires no "new-ing". No initialize is allowed. Just declare and use. This is my personal favorite and I use it a lot.
Usage:
var utils = ACNFoundation;
utils.listFactory(...);
Definition:
var ACNFoundation = Class.create();
ACNFoundation.listFactory = function (...) {};
For more information see: Ask the Expert: Scoped Libraries with Steve Bell (video)
3. Single Function Script Include
This is a somewhat uncommon type of Script Include. Most likely due to ignorance of use-cases where it would be applicable. This particular method shines as a scripted reference qualifier for constructing choice lists.
Usage:
Dictionary definition of a choice list field: Choice list reference qualifier
Definition: Name: getChoiceValues
function getChoiceValues(cat_item, variable) {
var choiceList = new GlideRecord('u_ucc_choices');
choiceList.addQuery('u_catalog_item', cat_item);
choiceList.addQuery('u_variable.name', variable);
choiceList.query();
var queryString = 'u_variable=';
if (choiceList.next()) {
queryString += choiceList.u_variable + '';
}
queryString += '^ORDERBYu_order';
return queryString;
}
For this example see: Mini-Lab: Service Catalog - Building a Custom Choice Table
However, used as a single function Script Include this would be the worst! Due to its non-extensibility. I consider this to be a code-review finding!
Usage: Called from BusinessRule, Scheduled Job, Script Action or any other Server side location.
Definition: Simple structure. By definition one function only. Named the same as the Script Include. This is essentially an implementation of the Class type.
Name: StevesLogging
StevesLogging = function(str) {
this.debug = true;
this.debugPrefix = '---> Steve!: ';
if (this.debug) {
gs.info(this.debugPrefix + str);
}
};
So great as a scripted reference qualifier, and terrible as a single function stand-alone Script Include.
4. Abstract Script Include
Definition: Scripted to specifically be an inherited (base) class that other classes extend. Designed to contain common functionality that will be inherited by all child classes. The AbstractAjaxProcessor is the poster-child for this type of class.
Usage: Used most often with Client-Server AJAX. Not all that common otherwise.
var AbstractAjaxProcessor = Class.create();
AbstractAjaxProcessor.prototype = {
CALLABLE_PREFIX : 'ajaxFunction_',
initialize : function(request, responseXML, gc) {},
process : function() {},
...
type: "AbstractAjaxProcessor"
}
5. Extends Script Include
Definition: Often used to extend the AbstractAjaxProcessor Script Include; which is always client callable. When used otherwise it does not have to be. This inherits a parent Abstract class along with all of the parent's functionality.
Must be new'ed.
Initialize is dangerous as it could override the underlying Abstract Script Include. So, be careful that you aren't overriding underlying parent functionality in the child. For example with Ajax you never use an initialize in the child as it exists in the parent and relies on it being there. Overriding it will break the Ajax functionality.
//Example 1:
// Ajax extensions cannot use initialize funciton (this overrides the AbstractAjaxProcessor initialize)
var ppm_int_TeamProcessor = Class.create();
ppm_int_TeamProcessor.prototype = Object.extendsObject(AbstractAjaxProcessor, {
createSprints: function () {},
...
});
Example 2:
This is a simple example of a facade extension (pass-thru). Facades are extremely useful as Abstract inheritance keeps the child from being used as a reusable library. Therefore, you push the actual functions down to a function or class Script Include used as a function library and "hollow-out" the child Script Include. The child becomes a facade as the real functionality resides in the reusable library. That allows the function library to then be used by other Server-side scripts.
//Example 2:
//This is a simple example of a facade extension. <<expand a little on this methodology>>
var ServiceInteractionUtils = Class.create();
ServiceInteractionUtils.prototype = Object.extendsObject(ServiceInteractionUtilsSNC, {
initialize: function() {
ServiceInteractionUtilsSNC.prototype.initialize.call(this);
},
type: 'ServiceInteractionUtils'
});
For a deeper dive into the facade model and advanced Ajax:
Mini-Lab: Using Ajax and JSON to Send Objects to the Server
Mini-Lab: Writing Entries Into the System Log Using Ajax and JSON
Mini-Lab: Converting a UI Script Library From Global to Scoped - Part 1
Mini-Lab: Converting a UI Script Library From Global to Scoped - Part 2
6. External Library Port Script Include
It is possible to drop an external library into a ServiceNow Scritp Include and have it extend the functionality. You have to be careful doing this. ServiceNow is ES5 (2011) and does not support functionality new than that! So, if your library has functions in it that are using new JavaScript features they will fail. I had to keep searching backward to find a version of Underscore.js that actually worked in ServiceNow!
See: Mini-Lab: Adding Underscore.js Into ServiceNow for more on how to do this.
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var
...
{return m})}).call(this);
//# sourceMappingURL=underscore-min.map
7. ServiceNow Object Extension Script Include
The intent here is to extend an existing platform or ServiceNow object. You simply use the JavaScript prototype capability to add functions and properties to the ServiceNow object, or any JavaScript object. Super simple. For more on this capability check out my book review on JavaScript the Good Parts.
Note that there is no class create or initialize with this. You are actually adding the functionality to the object. You would use the following at the end of the GlideRecord after the .query().
GlideRecord.prototype.toJSON = function() {
return new global.JSON().encode(this.toObjectList());
};
For more on extending ServiceNow objects:
Mini-Lab: Extending the GlideRecord Object
Mini-Lab: GlideRecord Between Query Extension
Mini-Lab: Adding a Select <<field>> to the Extended GlideRecord
8. Polyfill Script Include
Here is a very rare bird. This allows you to port a PolyFill into SN and extend the JavaScript language library. For example the padStart functionality from ECMA ES8 being added to the code base. These are dangerous due to their nature and the very real possibility of unsupported structure not being properly documented for support AND the eventual upgrade of SN to ES8 is the distant future. Basically it is NOT recommended that you do this. Just be aware that it CAN be done.
var StringPolyfill;
if (!String.prototype.padStart) {
/**
* Pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
*/
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length >= targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}
Another example:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisArg */) {...}
}
Understand that not everything can be dropped in as a polyfill. The underlying JavaScript platform does not support anything after JavaScript ES5 so it will require some messing around to get any newer features to work!
For more on polyfills:
Mini-Lab: Extending the JavaScript Array Object with findIndex
Mini-Lab: Extending ServiceNow JavaScript Using ECMAScript 6 Polyfills
Conclusion
Script Includes provide a seriously powerful tool to expand the functionality of the ServiceNow platform. Explore all of these on your Personal Develop Instance. You will be surprised at how easy it is to implement the various types. Get familiar with them as they all have their uses. ServiceNow is a PaaS and Script Includes are the key to unlocking the power of the platform!
Don't forget to check out my comprehensive list of articles here: Link
Enjoy!
Steven Bell.
If you find this article helps you, don't forget to log in and mark it as "Helpful"!
- 3,547 Views
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
