JavaScript DataSource Events and Callbacks

Every call to the DataSource read() method triggers a set of events that notify the start, completion, success and error states of the component.To register for events, use the events setting during initialization. Additionally, the read() method returns a jQuery Promise object that can be listened to using its then() method:

var ds = new shield.DataSource({
	data: [/*...*/],
	events: {
		start: function (e) {
			//e.params contains filter, sort, skip and take parameters
			//e.preventDefault() cancels the event from further executing
		},
		complete: function (e) {
			//triggered when the read operation completes successfully
		},
		change: function (e) {
			//triggered right after "complete" event
			//e.fromCache is true, if data is read from cache
		},
		error: function (e) {
			//triggered if there is an error during reading
			//e.error contains the error that is thrown
		}
	}
});
ds.read().then(function () {
	//success callback is called before the "complete" and "change" events
}, function() {
	//error callback is called before "error" event
});

The “start” and “complete” events mark the beginning and end of a single read operation (local or remote). The “start” event can be canceled, meaning that calling its event object’s preventDefault() method will abort the read operation and prevent any further events from firing.

The “change” event indicates data has been changed as a result of a successful read operation. The DataSource.view property is set by the time this event is fired and can be used to access the current view of the data after filter, sort, skip and take operations. As the result of filter, sort, skip and take operations are cached, a read() operation may return data from the cache instead of starting over. In this case the “change” event object has its fromCache property set to true to indicate data has been read from the cache.

The “error” event indicates an error occurred during a read operation and any data, if available, must be discarded. The event object’s error property contains the error that has been thrown during execution.

In addition to events, the DataSource.read() method returns a jQuery Promise object that can be listened to. The success callback of the promise is called when data is successfully read, just before the “change” event is fired by the component. The DataSource.view property is set to the current data view at this point.

Equivalently, the error callback of the promise is called just before the “error” event is raised by the component and indicates unsuccessful read operation.