Giter VIP home page Giter VIP logo

subscribe-ui-event's Introduction

subscribe-ui-event

npm version github actions

With subscribe-ui-event, instead of calling multiple window.addEventListener('scroll', eventHandler); by different components, call subscribe('scroll', eventHandler). It will only add a single event listener and dispatch event to those who subscribe to the event via eventemitter3.

Install

npm install subscribe-ui-event

Single Event Listener v.s. Multiple Event Listeners

Why a single event? More performant and less memory consumption.

The jsperf runs 10 addEventListener and 10 non-throttling subscribe, and the outcome is that the ops/sec of subscribe is slightly less. But in regular case, you will use throttling subscribe, and it will be more performant.

comparison

For 10 addEventListener, the difference of memory consumption between peak and trough is about 4.1K.

addEventListener

For 10 subscribe, the difference of memory consumption between peak and trough is about 1.0K.

subscribe

Other Benefits

  1. Throttling by default.
  2. Access document.body.scrollTop, window.innerWidth once.
  3. Provide requestAnimationFrame throttle for high performance.
  4. Be able to use events like scrollStart (see below) those edge events.

API

subscribe

subscribe(eventType: String, callback: Function, options: Object?): Subscription

Provide throttled version of window or document events, such like scroll, resize, touch and visibilitychange to subscribe, see below.

Note on IE8 or the below, the throttle will be turned off because the event object is global and will be deleted for setTimeout or rAF.

Example:

import { subscribe } from 'subscribe-ui-event';
function eventHandler (e, payload) {
    // e is the native event object and
    // payload is the additional information
    ...
}
// 50ms throttle by default
const subscription = subscribe('scroll', eventHandler);
// remove later
subscription.unsubscribe();

Optional Payload

The format of the payload is:

{
    type: <String>, // could be 'scroll', 'resize' ...
    // you need to pass options.enableScrollInfo = true to subscribe to get the following data
    scroll: {
        top: <Number>, // The scroll position, i.g., document.body.scrollTop
        delta: <Number> // The delta of scroll position, it is helpful for scroll direction
    },
    // you need to pass options.enableResizeInfo = true to subscribe to get the following data
    resize: {
        width: <Number>, // The client width
        height: <Number> // The client height
    },
    // you need to pass options.enableTouchInfo = true to subscribe to get the following data
    touch: {
        axisIntention: <String>, // 'x', 'y', or ''.
        startX: <Number>,
        startY: <Number>,
        deltaX: <Number>,
        deltaY: <Number>
    }
}

Options

options.throttleRate allows of changing the throttle rate, and the default value is 50 (ms). Set 0 for no throttle. On IE8, there will be no throttle, because throttling will use setTimeout or rAF to achieve, and the event object passed into event handler will be overwritten.

options.context allows of setting the caller of callback function.

options.useRAF = true allows of using requestAnimationFrame instead of setTimeout.

options.enableScrollInfo = true allows of getting scrollTop.

options.enableResizeInfo = true allows of getting width and height of client.

options.enableTouchInfo = true allows of getting touch information (see above).

eventType could be one of the following:

  1. scroll - window.scoll
  2. scrollStart - The start of window.scoll
  3. scrollEnd - The end of window.scoll
  4. resize - window.resize
  5. resizeStart - The start window.resize
  6. resizeEnd - The end window.resize
  7. visibilitychange - document.visibilitychange (IE8 doesn't support)
  8. touchmoveStart - The start of window.touchmove
  9. touchmoveEnd - The end of window.touchmove
  10. touchmove - window.touchmove
  11. touchstart - window.touchstart
  12. touchend - window.touchend

options.eventOptions: An options object that specifies characteristics about the event listener (if passive event is supported by the browser)

unsubscribe

unsubscribe(eventType: String, callback: Function): Void

Unsubscribe to an event listener, we suggest you use subscription.unsubscribe(), because it may accidentally unsubscribe those events having the same eventType and callback, but different throttleRate.

Credits

  • This library runs full browser test suite using Sauce Labs.

License

This software is free to use under the BSD license. See the LICENSE file for license text and copyright information.

subscribe-ui-event's People

Contributors

akshayp avatar dependabot[bot] avatar ebertb avatar frontsideman avatar gabeaudick avatar gertsallaerts avatar gfx avatar hankhsiao avatar kaesonho avatar redonkulus avatar rickyeh avatar roderickhsiao avatar scriptedalchemy avatar src-code avatar yachelee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

subscribe-ui-event's Issues

support passive event

a big/computation intensive touchStart, touchMove handler could block following scroll event.

Developers can now annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit.

in Chrome for Android 80% of the touch events that block scrolling never actually prevent it. 10% of these events add more than 100ms of delay to the start of scrolling, and a catastrophic delay of at least 500ms occurs in 1% of scrolls.

spec:
https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://dom.spec.whatwg.org/#dom-eventlisteneroptions-passive

scroll performance comparison between passive:true and false
https://www.youtube.com/watch?v=NPM6172J22g

polyfill

// Test via a getter in the options object to see 
// if the passive property is accessed
var supportsPassive = false;
try {
  var opts = Object.defineProperty({}, 'passive', {
    get: function() {
      supportsPassive = true;
    }
  });
  window.addEventListener("test", null, opts);
} catch (e) {}

// Use our detect's results. 
// passive applied if supported, capture will be false either way.
elem.addEventListener(
  'touchstart',
  fn,
  supportsPassive ? { passive: true } : false
); 

react is yet to support passive event
facebook/react#6436

The throttledEndEvent doesn't get emitted when using a different target

In connectContinuousEvent, when using a different domTarget (via specifying an options.target value), the throttledEndEvent doesn't get emitted when endCallback is called.

In my case, the EE.emit function was looking for the "scrollEnd:50" event, when only the "scrollEnd:50:scrollable-div" event was there. Looking at the code, I think the same thing will happen for the throttledStartEvent.

I was able to get it to work for my case by adding the (domId ? ':' + domId : '') to the throttledEndEvent -- like what was recently added to the throttledMainEvent and throttledEvent.

var throttledStartEvent = mainEvent + 'Start:' + throttleRate;
var throttledEndEvent = mainEvent + 'End:' + throttleRate + (domId ? ':' + domId : '');
var throttledMainEvent = mainEvent + ':' + throttleRate + (domId ? ':' + domId : '');
var throttledEvent = event + ':' + throttleRate + (domId ? ':' + domId : '');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.