Created
March 3, 2013 18:01
-
-
Save falsefalse/5077303 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Transport = function(methods) { | |
var fn = function(options) { | |
this.options = options || {}; | |
}; | |
_.extend(fn.prototype, Transport.prototype, methods); | |
return fn; | |
}; | |
_.extend(Transport.prototype, Backbone.Events, { | |
// stub | |
validate: function(parsed) { return true; }, | |
parse: function(data) { | |
var parsed; | |
// parse the data, we have JSON and regular HTML undistinguished here | |
try { | |
parsed = JSON.parse(data); | |
} catch (e) { | |
// can't parse as JSON - treat it as raw html string | |
parsed = { html: data }; | |
} | |
return parsed; | |
}, | |
request: function(options) { | |
options = options || {}; | |
var dfd = _.Deferred(); | |
if (this.options.success) dfd.done(this.options.success); | |
if (this.options.failure) dfd.fail(this.options.failure); | |
// make sure we don't send shit along the way, | |
// it breaks advertisier's CORS | |
$.ajaxSettings.beforeSend = function(xhr) { | |
xhr.withCredentials = false; | |
}; | |
var context = this.options.context || this; | |
$.ajax({ | |
url: options.url, | |
context: this, | |
success: function(data) { | |
var parsed = this.parse(data); | |
if ( this.validate(parsed) ) { | |
dfd.resolveWith(context, [parsed, options]); | |
} else { | |
dfd.rejectWith(context, ['No data received', options.url]); | |
} | |
}, | |
error: function(status, xhr, settings) { | |
dfd.rejectWith(context, [status, options.url]); | |
} | |
}); | |
return dfd; | |
} | |
}); | |
var AdTransport = Transport({ | |
validate: function(parsed) { | |
return !!(parsed.html || parsed.url && (parsed.img.src || parsed.img.src_alt)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment