David Ferris
David Ferris

Reputation: 2325

Scroll Detection in Ember JS?

What's the best way to detect scrolling in Ember JS? There is no built in scroll action, and I can use jquery but not sure where to place it? Would it go in my application.js because it has application scope, or elsewhere?

The actual scroll detection/logic is not an issue here, but rather how to set up scripts like this in an Embery way.

Ideally scrolling would be an action, and could be handled as such in the application.js file:

import Ember from 'ember';

export default Ember.Route.extend({
    actions: {
        onScroll: function() {
            alert('scrolled');
        }
    }
});

Upvotes: 3

Views: 4084

Answers (2)

David Ferris
David Ferris

Reputation: 2325

I ended up using this awesome library, ember-perfectscroll. It wraps the necessary templates, and provides a ton of useful CSS classes/functions.

Upvotes: 2

n1ru4l
n1ru4l

Reputation: 498

At work we used the lifecycle hooks to register/unregister event that are not implemented in Ember. We used the didInsertElement and willDestroyElement lifecycle hooks to bind/unbind jQuery events to a specific namespace (often the components ID): https://guides.emberjs.com/v2.8.0/components/the-component-lifecycle/

Code example:

import Ember from 'ember';

export default Ember.Component.extend({

  didInsertElement() {
    this._super(...arguments)

    // Register your events here
    Ember.$(document).on('scroll.my-namespace', 'body', this.eventHandler)
    // this.$ if the element is located inside the component
    },

  willDestroyElement() {
    this._super(...arguments)

    Ember.$(document).off('scroll.my-namespace')
    // this.$ if the element is located inside the component
  },

  eventHandler(ev) {
      //Do sth with event
  }

})

An alternative way could be a service which extends Ember.Evented. IN that service you could also register a jQuery Event listener. The components which need to listen to the scroll event could subscribe to the service (http://emberjs.com/api/classes/Ember.Evented.html).

Upvotes: 7

Related Questions