Skip to content

Instantly share code, notes, and snippets.

@alexblom
Created January 25, 2015 19:35
Show Gist options
  • Save alexblom/542146992ed939803423 to your computer and use it in GitHub Desktop.
Save alexblom/542146992ed939803423 to your computer and use it in GitHub Desktop.
Ember Data Adapter (HTTP Request Handling) for Firefox Extension /w Add-on SDK
import Ember from "ember";
import DS from 'ember-data';
export default DS.ActiveModelAdapter.extend({
ajax: function(url, type, hash) {
var browser, adapter;
adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var options = {};
options.url = url;
options.type = type;
options.data = hash.data;
//self is reserved in firefox ext, refers to the addon
//see https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/self
self.port.on(url, function(status, json) {
if (status === 200) {
Ember.run(null, resolve, json);
} else {
Ember.run(null, reject, adapter.firefoxError(status));
}
});
self.port.emit("http-req", options);
});
},
firefoxError: function(error) {
return {status: status};
}
});
var pageMod = require("sdk/page-mod");
var Request = require("sdk/request").Request;
pageMod.PageMod({
onAttach: function(port) {
portListeners(port);
}
});
function portListeners(port) {
port.port.on("http-req", function(options) {
var req = Request({
url: options.url,
content: options.data,
onComplete: function (response) {
port.port.emit(options.url, response.status, response.json);
}
});
switch (options.type) {
case "GET":
req.get();
case "PUT":
req.put();
case "POST":
req.post();
case "DELETE":
req.delete();
}
});
}
@alexblom
Copy link
Author

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