mharris717 / ember-drag-drop

Drag and Drop Addon for Ember CLI
MIT License
204 stars 141 forks source link

"no obj for key" error #216

Open xtagon opened 1 year ago

xtagon commented 1 year ago

Drag and drop actions throw an error if the payload being dropped is not a draggable object, such as if it is a text node being dragged.

This same error is reproduced in various other ways in these issues:

https://github.com/mharris717/ember-drag-drop/issues/157

https://github.com/mharris717/ember-drag-drop/issues/101

https://github.com/mharris717/ember-drag-drop/issues/21

https://github.com/mharris717/ember-drag-drop/issues/62

And previously this was "fixed" but not completely, in:

https://github.com/mharris717/ember-drag-drop/pull/96/files

The error is not catchable in the @action handlers because the error prevents that action from being sent, so the only workaround is to monkey patch the DraggableObjectTarget component.

One workaround is to extend DraggableObjectTarget with:

import DraggableObjectTarget from 'ember-drag-drop/components/draggable-object-target';

function isNoObjForKeyError(error) {
  return error && error.message && error.message.startsWith("no obj for key ");
}

export default DraggableObjectTarget.extend({
  // See https://github.com/mharris717/ember-drag-drop/blob/v0.9.0-beta.0/addon/components/draggable-object-target.js#L22-L25
  handlePayload(payload, event) {
    let obj;

    try {
      obj = this.get('coordinator').getObject(payload,{target: this});
    } catch (error) {
      if (isNoObjForKeyError(error)) {
        // Intentionally suppress this error so it doesn't throw on non-object
        // drops (e.g. if you drag and drop text instead of a draggable object)
      } else {
        throw error;
      }
    }

    if (obj) {
      this.get('action')(obj, { target: this, event: event });
    }
  }
});

An alternative would be to send the action even if obj is null or undefined, for those of you who want to accept non-object drops.