Tip #854: Beware of Using Xrm Client Functions As Callbacks

Today’s tip comes from the tipper who, despite his affinity with Microsoft Flow, earned his place amongst the real developers fair and square, and who is now known as Daryl “Always Raising” LaBar.

Daryl, you have the floor

Writing clean code is constantly at the for-front of developers, and usually, “less” code generally results in “cleaner” code. So when coding on-change event’s it’s very typical to see code like this:

Xrm.Page
  .getAttribute("fieldname")
  .addOnChange(Xrm.Page.ui.refreshRibbon);

favored over code like this:

Xrm.Page
  .getAttribute("fieldname")
  .addOnChange(function (){ 
	Xrm.Page.ui.refreshRibbon(); 
  });

(or even for the “cooler” JavaScript developers)

Xrm.Page
  .getAttribute("fieldname")
  .addOnChange(() => { 
    Xrm.Page.ui.refreshRibbon(); 
  });

Which works great, until it doesn’t. And it doesn’t work great in the interesting case when calling refresh, which then triggers a previously defined onChange event. In this particular scenario, the Xrm object model defined as the callback handler is no longer valid, due to a new one taking it’s place.

This would result in the code from the first example throwing this error: “Unable to get property ‘refreshRibbon’ of undefined or null reference”, but the second and third examples would execute normally as expected. This is because the callback is pointing to a function, which gets the current version of window.Xrm, which is valid, unlike the first example, where the call back is pointing to a specific version of Xrm (and in this scenario, an older invalid version).

So feel free to be “cute” in your OnChange callbacks… just not “too cute” and remember: Friends don’t let friends create onChange events pointing directly to Xrm functions.

Tipp Jaar’s $0.02 + tax

I don’t believe the last syntax, however cool and cute it is, would work in an obscure browser called Internet Explorer, including version 11. But then again, as the name suggests, that browser is for exploring Internet and not for doing any work around Dynamics 365.

Tweet about this on TwitterShare on Facebook0Share on Google+0

One thought on “Tip #854: Beware of Using Xrm Client Functions As Callbacks

  1. Daryl LaBar says:

    Of course it would work in IE, because I wrote it in TypeScript, which is setup to transpile into something that even IE 11 can understand!

Leave a Reply

Your email address will not be published. Required fields are marked *