Dynamic Variable Values

How to keep your variables up to date

Overview

You may come across use cases that call for ensuring that your variables are up to date. This is most relevant when a user may have performed an activity that changed a value of a variable after the block has been loaded onto the screen. Examples of this would be if a user signs in/out (thus changing the user variables), or if a product is added to the cart (thus changing the cart variables).

To keep your solution reactive to any dynamic variable changes, you can utilize a built event handler in your JS. By using this handler & specifying the variable object you are subscribing to, you will always be kept in the know if a variable value happens to change. As a result, you'll receive an updated payload containing only the fields that happened to change.

registerEventHandler

By using the registerEventHandler helper function, you can update your variables, should their values change in real-time.

registerEventHandler out of the box setup

Tapcart.registerEventHandler(event, function(eventData) {
// include logic for what you want to do when the variable changes
});

The event param represents the event to subscribe to, you can replace it with any of the following options:

  • "product/updated"
  • "customer/updated"
  • "cart/updated"

registerEventHandler used with Handlebars.js

Handlebars.registerHelper('json', function(context) {
    return JSON.stringify(context,null,2);
});

const source = `
  <div>the Variables Test Block</div>
  <pre style="white-space:pre-wrap;word-break:break-all;">{{json this}}</pre>
`

let extraDiv = document.querySelector("#extra");
let extraTemplate = Handlebars.compile(source);
extraDiv.innerHTML = extraTemplate(Tapcart.variables)

Tapcart.registerEventHandler("product/updated", function(eventData) {
  Handlebars.compile(source);
  extraDiv.innerHTML = extraTemplate({...Tapcart.variables,...eventData})
  Tapcart.actions.showToast({
    type: "success",
    message: "Event occurred: \"product/updated\""
  })
});
Tapcart.registerEventHandler("customer/updated", function (eventData) {
  Handlebars.compile(source);
  extraDiv.innerHTML = extraTemplate({...Tapcart.variables,...eventData});
  Tapcart.actions.showToast({
    type: "success",
    message: "Event occurred: \"customer/updated\""
  })
});
Tapcart.registerEventHandler("cart/updated", function (eventData) {
  Handlebars.compile(source);
  extraDiv.innerHTML = extraTemplate({...Tapcart.variables,...eventData});
  Tapcart.actions.showToast({
    type: "success",
    message: "Event occurred: \"cart/updated\""
  })
})