Similar to the promises pattern I'm looking for an event pattern that avoids needing to pollute objects with addEventListener/etc methods, I want to be able to return an object, that can be cancelled as well as 'resolved' multiple times.
For example, I may write a method that returns an 'interval' object, something like this:
var ticker = createTicker(1000);
var subscription = ticker.then(function() { console.log('tick') });
... later on ...
sub开发者_JAVA百科scription.cancel();
The key differences here being, similar to a promise the events are standardized, so that I can subscribe without needing to know the event name, however unlike a promise, the "completion" can happen multiple times, and may even be cancelled (this would be equiv of removeEventListener).
I'm interested to see if this is legal with promises, such that the progress handler could be used for multiple callbacks, and the complete handler never used, but more importantly, that there is a concept of unsubscribing from a promise.
If this isn't the case, and promises are specialized to this scenario, is there a standardized pattern for doing what I described?
The ability to cancel can be added to a promise implementation, without breaking the main paradigm of having single-fire success/failure callbacks.
In fact, jQuery already has cancellation for the promise instances that it returns from jQuery.ajax
calls:
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
- readyState
- status
- statusText
- responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
- setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
- getAllResponseHeaders()
- getResponseHeader()
- abort()
You could write a setTimeout
wrapper that exposes a promise interface along with an additional cancel method.
However, once you get into the multi-fire territory, I think that is not what promises are intended for. You would have to define a lot of rules and exceptions around how multiple firing will play out alongside regular promise functionality. It doesn't make a lot of sense to me to use promises that way.
Update (based on discussion in comments):
Here's a sample implementation of a promise "proxy" that allows aborting further relaying of the done/fail callbacks:
http://jsfiddle.net/atesgoral/qvtqu/
精彩评论