根据触发用户事件的上下文限制执行

在 SuiteScript 1.0 中,我们使用 nlapiGetContext().getExecutionContext() 检索当前执行上下文,然后我们将结果与适当的原始字符串进行比较。

// 1.0 in Revealing Module pattern
var myNamespace = myNamespace || {};
myNamespace.example = (function () {
    var exports = {};
    
    function beforeLoad(type, form, request) {
        showBonusEligibility(form);
    }
    
    function showBonusEligibility(form) {
        // Doesn't make sense to modify UI form when the request
        // did not come from the UI
        var currentContext = nlapiGetContext().getExecutionContext();
        if (!wasTriggeredFromUi(currentContext)) {
            return;
        }
        
        // Continue with form modification...
    }
    
    function wasTriggeredFromUi(context) {
        // Current context must be compared to raw Strings
        return (context === "userinterface");
    }
    
    function isEligibleForBonus() {
        return true;
    }
    
    exports.beforeLoad = beforeLoad;
    return exports;
})();

在 SuiteScript 2.0 中,我们通过导入 N/runtime 模块并检查其 executionContext 属性来获取当前执行上下文。然后,我们可以将其值与 runtime.ContextType 枚举的值进行比较,而不是将原始字符串进行比较。

// 2.0
/**
 * @NScriptType UserEventScript
 * @NApiVersion 2.x
 */
define(["N/ui/serverWidget", "N/runtime"], function (ui, runtime) {
    var exports = {};
    
    function beforeLoad(scriptContext) {
        showBonusEligibility(scriptContext.form);
    }
    
    function showBonusEligibility(form) {
        // Doesn't make sense to modify the form if the 
        if (!wasTriggeredFromUi(runtime.executionContext)) {
            return;
        }
        
        // Continue with form modification...
    }

    function wasTriggeredFromUi(context) {
        // Context can be compared to enumeration from runtime module
        return (context === runtime.ContextType.USER_INTERFACE);
    }
    
    exports.beforeLoad = beforeLoad;
    return exports;
});