Blackbox widgets

83 views
Skip to first unread message

Phred Lane

unread,
Oct 5, 2015, 4:28:56 PM10/5/15
to Polymer
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.

Aleks Totic

unread,
Oct 5, 2015, 7:32:48 PM10/5/15
to Polymer
In this pattern, I'd prefer callbacks to promises, something like:

this.fire('share-item',{id, target, message, callback(err, result});

Promises are still not mainstream, and callbacks are well understood.

Aleks

Phred Lane

unread,
Oct 19, 2015, 11:00:02 AM10/19/15
to Polymer
Thanks for the reply. I believe promises are a better pattern to tackling asynchronous workflow. The only problem with promises, in my opinion, is people aren't using them enough.

I really wanted feedback on the blackbox widget development more than promises vs callbacks though.
Reply all
Reply to author
Forward
0 new messages