Ask a Jedi: Doing arithmetic with Spry data

Hi, I'm trying to do some arithmetic with Spry the data is coming from a dataset. Now how can I loop through the dataset and then add to get a total. For example in ColdFusion I can do this:
<cfset totalA = 0>
<cfset totalB = 0>
<cfloop query="test">
<cfset totalA = totalA + amountA>
<cfset totalB = totalB + amountB>
</cfloop>
and this will give me the totals, but in Spry I can't seem to find a way to do this. Any help you can give me will be appreciated. Thanks!

This can be done by using an observer on the dataset. An observer is basically a way to monitor the life cycle of a dataset. One thing you can monitor is when the data is done loading. Once the data is done, we can then look at it and make our own totals. First let’s look at a simple example without the observer:

The observer is an object with the particular method (onPostLoad) as a property. Skip over the function code and notice how it is added to my dataset. So basically I’ve said: “When you are done loading, run this function and pass in the dataset.” The meat of the function is just a simple loop. I get the raw data. Loop over it. (Note the parseInt to treat the age as a number.) Finally I update a div with the result. The complete code is below.

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos.
If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.