JavaScript DataSource Binding to Remote Data

Shield UI DataSource supports binding to remote web services. The remote.read initialization options provide configuration for reading from remote a web service:


var ds = new shield.DataSource({
	remote: {
		read: {
			url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=b9z6zc9p7yut8cjen5bjpc4b",
			dataType: "jsonp",
			data: function () {
				return {
					q: "Harry Potter"
				}
			}
		},
		cache: true
	},
	events: {
		change: function () {
			var view = ds.view;
			//do something with the data
		}
	}
});
ds.read();

The remote.read.url setting specifies the remote URL to read from. When Shield UI DataSource is configured for remote binding, it makes an XMLHttpRequest to the remote endpoint when the component’s read() method is called. In this process, the object specified by remote.read is passed directly to the jQuery.ajax method. This means that you can specify additional AJAX settings in the remote.read object that jQuery.ajax() will understand. Relying on jQuery for remote requests means Shield UI DataSource provides a well-known, predictable configuration model for remote web service binding.

The only major difference between the format of a remote.data object and a jQuery.ajax() settings objects is that the remote.read.data setting specifies a function that accepts the remote filter, sort, skip and take parameters in a single object and returns another JavaScript object that is passed to data field of settings object provided to jQuery.ajax(). Key-value pairs from this object are then translated by jQuery to query string parameters for GET requests or post data for POST HTTP requests. This mechanism allows mapping data transformation parameters from shield UI DataSource to parameters that the remote web service will understand:


$(function () {
	var ds = new shield.DataSource({
		remote: {
			read: {
				url: "http://services.odata.org/V3/Northwind/Northwind.svc/Products?$format=json",
				data: function(params) {
					var dataObject = {};
					
					if (params.skip != null) {
						dataObject.$skip = skip;							
					}
					
					if (params.take != null) {
						dataObject.$top = take;
					}
					
					return dataObject;
				}
			}
		},
		schema: {
			data: "value"
		},
		skip: 5,
		take: 7
	});

	ds.read().then(function () {
		var view = ds.view;
		
		view.forEach(function(item) {
			console.log(item);
		});
	});
});