Newer Version Available
Remote Objects Callback Functions
Remote Objects sends all requests to the Salesforce service asynchronously. Your code handles responses to Remote Objects operations in a callback function that you provide. Callback
functions handle updating the page with the results of the operation
and errors that are returned.
Callback functions are a standard technique in JavaScript for handling events and asynchronous operations. Remote Objects uses this pattern to handle the response of its asynchronous operations. When you invoke a Remote Objects operation, you provide the parameters of the operation and, optionally, a callback function. Your JavaScript code continues uninterrupted after you invoke the operation. When the remote operation is completed and results are returned, your callback function is invoked and receives the results of the operation.
Remote Objects callback functions can be written to receive up to three arguments.
Most callback functions check for errors and then take an
action with the results. The event object is typically used only in debugging and sophisticated error
management.
1function callback(Error error, Array results, Object event) { // ... }| Name | Type | Description |
|---|---|---|
| error | JavaScript Error object | A standard JavaScript Error object. If the operation succeeded, error is null. Use error.message to retrieve the reason for a failure. |
| results | JavaScript array | An array that contains the results of the operation. If the operation was a retrieve(), the results are instances of the appropriate Remote Objects. Otherwise, the array contains strings that represent the Ids of affected records. |
| event | JavaScript object | A JavaScript object that provides the details of the JavaScript remoting event transporting the Remote Objects operation. |
Example
Here’s a straightforward callback function, which
handles the results of a retrieve() operation.
In this sample, getAllContacts() calls retrieve() and passes
an anonymous function as the callback. The callback function checks
for errors and then uses jQuery to iterate through the array of result
records, adding them to the page. Some details are omitted to focus
on the callback structure. See An Example of Using Remote Objects with jQuery Mobile for the complete page source code.
1function getAllContacts() {
2 $j.mobile.showPageLoadingMsg();
3
4 var c = new RemoteObjectModel.Contact();
5 c.retrieve({ limit: 100 }, function (err, records) {
6 // Handle errors
7 if (err) {
8 displayError(err);
9 } else {
10 // Add the results to the page
11 var list = $j(Config.Selectors.list).empty();
12 $j.each(records, function() {
13 var newLink = $j('<a>'+this.get('FirstName')+' '+this.get('LastName')+'</a>');
14 newLink.appendTo(list).wrap('<li></li>');
15 });
16
17 $j.mobile.hidePageLoadingMsg();
18 list.listview('refresh');
19 }
20 });
21}