Search code examples
javascriptfunctionadobeadobe-analytics

Sourcing Global Function from an Anonymous Function that Returns in Adobe DTM


The below code snippets are not the actual code, they are only there to explain my issue. So please don't concentrate on the actual functionality. I'm working with Adobe DTM. I have no idea how to get an anonymous function that returns a value (as a Data Element to source a global function? If I have a normal anonymous function within my data Element, everything works fine. If the anonymous function returns, then it doesn't work? Is there any way to get this to work? Example:

//global function
function _myGlobalFunct(str){
return (str);
}

the following code of an anonymous function within the Data Element calls global function and it works as expected:

// working anonymous function
 (function () {
 window._myGlobalFunct("value1");
 })()

but the following return anonymous function, within the Data Element, doesn't call my function but doesn't throw any errors? :

// Not Working Properly but doesn't throw any errors?
return (function() { 
var rvalue = document.title || "No Title";
window._myGlobalFunct(rvalue);
return rvalue;
})();

I do know the function is executing but not getting any errors in Chrome?


Solution

  • DTM's data elements execute the code provided within a function (that may not be clear to the other users here), so there will be a return outside of a function in the code you input/show here. You're not returning the value from your function (or if you're trying to update rvalue within the function and rvalue isn't in the right scope (window vs. local)). In any case, is there a reason you're using the anonymous function anyways? Below should work:

    var rvalue = document.title || "No Title";
    return window._myGlobalFunct(rvalue);
    

    If you still want the anonymous function, make sure to grab the return value from your function:

    return (function() { 
      var rvalue = document.title || "No Title";
      return window._myGlobalFunct(rvalue);
    })();