Skip to content

Instantly share code, notes, and snippets.

@davethegr8
Last active December 28, 2015 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davethegr8/7492387 to your computer and use it in GitHub Desktop.
Save davethegr8/7492387 to your computer and use it in GitHub Desktop.
BatChannel.js - a system for batching ajax requestsassumes (requires) that your server side code can handle routing the urls on it's own, and responds with something like this: { success: (true | false), ...other data.. }
//(c) 2013 Dave Poole zastica.com
//BatChannel.js - a system for batching ajax requests
//
//assumes (requires) that your server side code can handle
//routing the urls on it's own, and responds with something
//like this: { success: (true | false), ...other data.. }
var BatChannel = function(endpoint, interval) {
this.endpoint = endpoint;
this.pending = [];
this.interval = interval || 30000;
this.tick();
};
BatChannel.prototype = {
request: function(url, data, callback) {
var promise = $.Deferred();
promise.done(callback);
this.pending.push({
url: url,
data: data,
promise: promise
});
return promise;
},
send: function() {
if (!this.pending.length) return;
//copy the pending items and clear the queue for new requests
var messages = this.pending.slice();
this.pending = [];
//send the request. Server is responsible for returning a matching array
//we don't fret the callbacks, because JSON will skip them
var data = JSON.stringify(messages);
var xhr = $.ajax(this.endpoint, {
type: 'POST',
dataType: "json",
data: data
});
xhr.done(function (response) {
for (var i = 0;i<response.length; i++) {
messages[i].promise.resolve(response[i].data);
}
});
},
tick: function() {
this.send();
setTimeout(this.tick.bind(this), this.interval);
}
};
// Creates a channel where the client and server can interact
var Channel = new BatChannel('/api/');
// Adds a request to the channel for friends data
Channel.request('getFriends').done(function(friends) {
console.log('Friends Done: ', friends)
});
// Adds a request to the channel for users data
Channel.request('getUsers').done(function(users) {
console.log('Users Done: ', users)
});
// This is cleaner, but it's noisy and makes 2 server requests
$.ajax('/api/getUsers').done(function(users) {
console.log('Users Done: ', users)
});
$.ajax('/api/getFriends').done(function(friends) {
console.log('Friends Done: ', friends)
});
@davethegr8
Copy link
Author

Now using jquery promises

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment