In a previous post on the subject of customizations we explored some general tips and advice that help us avoid a variety of problems. We will continue this discussion, but this time around we will focus on JavaScript. More specifically, we will focus on the manner in which one can handle responses to requests made to the Sugar REST v10 API.
One may have a need to send such a request to:
- Read an existing record
- Update a record
- Load a collection
The Sidecar framework provides mechanisms for performing all of the above, such as beanObject.fetch(). However, the process for handling responses these methods generate is not readily obvious. Quite often, there is a tendency to rely on raw JavaScript to address such needs, for example, interacting with the xhr object as such:
object.xhr.done()
Rather than using raw JavaScript, one should leverage the parameters that can be defined as part of the method. In the case of .fetch(), it would look similar to the following:
As illustrated in the code, an anonymous function is defined for the success: parameter. This is the code that will be automatically executed upon a response being received and is capable of interacting with the JSON response -- found in the data variable.
Note that a similar approach can also be used to define an error anonymous.