根據觸發使用者事件的上下文限制執行

在 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;
});