Reading a Custom Control Property Into Client-Side JavaScript

There are times when it’s helpful to get information from server-side JavaScript into client-side JavaScript. I find this most frequently when I have a custom control that uses a client-side library function, but needs information from a back-end document to work with. (For example, generating a chart with a client-side script library and plotting information from documents on the chart.)

“#{javascript: }” Syntax

If you have a custom control that accepts custom properties and needs to include them in client-side JavaScript, one method you have available to you is this syntax:

"#{javascript: SSJS_CODE_HERE}"

The server will evaluate the code between the colon (:) and closing curly brace (}) on the server side and replace the entire value between (and including) the quotes with the value that results from the server-side JavaScript statement.

Custom Properties

To get a custom property from a custom control, you can use the compositeData object. It automatically provides a handle to all custom properties passed to the custom control.

To get a custom property named myProperty in SSJS, you would use this statement:

var x = compositeData.myProperty;

So, to read the value of a custom control property into a client-side JavaScript statement, you just combine these two things:

var x = "#{javascript:compositeData.myProperty}";

Make sure it’s within an xp: tag

Even though the end result is client-side JavaScript, it requires server-side processing before the page is rendered, so this will *only* work within xp: tags. It will work within an xp:scriptBlock tag, but it will not work with pass-through JavaScript, such as a tag.

<xp:scriptBlock id="block1">
  var x = "#{javascript:compositeData.myProperty}";
</xp:scriptBlock>
Advertisements

2 responses to “Reading a Custom Control Property Into Client-Side JavaScript”

  1. Tim Tripcony (@timtripcony) says :

    In expressions like these, where you’re just referring to a single object property, you can nearly always drop the javascript prefix:

    #{compositeData.myProperty}

    Every time you do this, you gain a little bit of extra efficiency, which in high-volume apps can add up enough to be noticeable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: