[RxJS] Creation operators: fromEventPattern, fromEvent

Besides converting arrays and promises to Observables, we can also convert other structures to Observables. This lesson teaches how we can convert any addEventHandler/removeEventHandler API to Observables.

 fromEvent(target, EventType):
var foo = Rx.Observable.fromEvent(document, 'click');

foo.subscribe(function (x) {
  console.log('next ' + x);
}, function (err) {
  console.log('error ' + err);
}, function () {
  console.log('done');
});

fromEventPattern(addEventHandler, removeEventHandler): take two functions

function addEventHandler(handler){
  document.addEventListener('click', handler)
}

function removeEventHandler(handler){
  document.removeEventListener('click', handler)
}

var foo = Rx.Observable.fromEventPattern(addEventHandler, removeEventHandler);

foo.subscribe(function (x) {
  console.log('next ' + x);
}, function (err) {
  console.log('error ' + err);
}, function () {
  console.log('done');
});
原文地址:https://www.cnblogs.com/Answer1215/p/5389543.html