I'm making an application that functions as a front end for a service. It doesn't do any work itself. It just let's the outter page know that it wants things to be done through events.
For instance, it fires events like:
this.fire('delete-item', {id});
this.fire('edit-item', {id, title});
this.fire('share-item',{id, target, message});
If the request can fail or I care about the response, I have a wrapper around `this.fire` that fires with a deferred object and the data. This is so I can show the end user feedback "Deleted X items successfully" or "Failed to update the title for Y".
this.firePromise('delete-item', {id});
this.firePromise('edit-item', {id, title});
this.firePromise('share-item',{id, target, message});
For reference, this is the definition of the Promisable mixin:
Polymer.Promisable = {
defer: function() {
return Q.defer();
},
firePromise: function(name, data) {
var deferred = this.defer();
deferred.data = data;
this.fire(name, deferred);
return deferred;
}
};
The otuter page catches the events, does the needful, and resolves/rejects the promise as needed. Here's an example:
widget.addEventListener('delete-item', function(e) {
var deferred = e.detail;
var data = deferred.data;
fetch(`/rest/endpoint/items/${data.id}`, deleteOptions)
.then(function(result) {
deferred.resolve();
widget.items = result.items;
})
.catch(deferred.reject)
;
});
I'm not responsible for making the requests to the backend myself, because the goal is for me not to care. I'm just expressing how I want the data to be managed.
Is this a weird pattern? Is there an alternative (better and/or more Polymer-esque) way to get the same functionality? I don't want to use fetch wrapped in an element, because I don't care if they use fetch, $.ajax, or any other method to get the data. I want them to be free to handle my events as they see fit.
I'm generally just looking for feedback on this pattern.