We interrupt our regular schedule for a very quick tip today, one that I learned about just last week: you can pass data into the getVar()
method, and use that data inside your Custom Code Data Element!
I learned about that from fellow #measure slack contributor Francis Li, and, somewhat embarrassing, should’ve seen it a lot earlier, because my colleague Ben Wedenik had used it for some time, and I had even reviewed his post and it had slipped through.
I don’t want this to happen to any of you, so this post is to call out that and how you can do that.
Francis Li described it very well on slack, here is a screenshot (with his permission)
Why?
Why is this cool? What do you do with it?
Two use cases that spring to mind are lookups and functions.
You can put a function into a Data Element, then use that function where you need it.
This would be the DE, obviously a Custom Code DE. Let’s call it ‘myAdd’
return function (a, b) { return a + b; }
And this is how you’d use it in code somewhere else:
var value1 = 2; var value2 = 2; var add = _satellite.getVar('myAdd'); var sum = add(value1, value2); // sum would now be 4
The Data Element is used here as a container, simple storage. We retrieve something from it, then use that something.
Javascript is extremely chill about types, and that makes it possible to do this. But it feels wrong, not very encapsulated. Wouldn’t it be nice if the DE took parameters, and if we did the work inside the DE?
Well, we can!
How?
Same DE as above, and here is the code:
// two parameters: termOne, termTwo // the result will be the sum of those two return event.termOne + event.termTwo
Yes, in real life scenarios, you’d likely add checks, like Francis did in his example.
And how do you use this marvel?
var result = _satellite.getVar('myAdd', {'termOne': 2, 'termTwo': 2});
Nifty, isn’t it?
Whatever it is that you pass into the getVar()
method can be used by accessing the event
object.
![[screenshot]](https://webanalyticsfordevelopers.files.wordpress.com/2020/11/201201-using-the-de.png?w=656)
Notes
Francis was asking about documentation, that’s how this all started. There is documentation, now, thanks to Yuhui, and there is also the (open) source of the Core Extension itself, on GitHub.
Nice work, Stewart, and thank you, Francis, for bringing it up!
I’d love to see your (your!) fancy use cases, too!
Nice one! Seen this before (stumbled across this in a project) and was amazed.Definitely worth for any Launch developer to know!
What would be awesome: A way to use this directly in the UI, passing other data elements as values (something like %myAdd,{[val1],[val2]}% with val1 and val2 being other data elements)…Pretty sure there is no current way for this, or is there?
LikeLike