Skip to content

Allow listening to DOM events #17

@robinplace

Description

@robinplace

Implementing, for example, a draggable element would be so nice like this:

const DraggableView = AmpersandView.extend ({
  ...
  events: {
    'mousedown': 'down', // start dragging and set listeners
  },
  down: function (ev) {
    ...
    // we need to listen on window to handle panning outside the browser
    this.listenTo (window, 'mousemove', this.move)
    this.listenTo (window, 'mouseup', this.up)
  },
  move: function (ev) {
    ...
  },
  up: function (ev) {
    ...
    // this is way elegant!
    this.stopListening (window, 'mousemove')
    this.stopListening (window, 'mouseup')
  },
})

Being able to do this would have huge advantages over other solutions:

  • Defining mousemove and mouseup in the events hash causes atrocities like the element being left behind if the mouse if moved too fast, or being stuck dragging if the mouse is moved outside the window.
  • Using .listenTo preserves the context for this in the callback function.
  • The event listeners would be removed when the view was destroyed.
  • The .stopListening is way more elegant than the DOM's .removeEventListener

I think implementing this should be just as simple as modifying ampersand-events to allow .listenTo and .stopListening on DOM elements. I think the code to stop listening on destruction is already in place and wouldn't need modification.

What do you think? Surely you cannot deny the awesomeness of what this would allow you to do; is this as simple to implement as it seems?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions