Kieran E
Kieran E

Reputation: 3666

Best way to create an unknown number of JackUp instances

We're using JackUp for ajax image upload in Rails. We chose it because it doesn't assume very much and it's pretty light weight.

Following it's example code, we came up with something like this:

  let jackUp = new JackUp.Processor({
    path: '/images'
  });

  jackUp.on('upload:imageRenderReady', (e, options) => {
    options.image.attr("data-id", options.file.__guid__).css({
      border: "5px solid red"
    });
    $('[data-behavior=image-block-container]').prepend(options.image);

  }).on("upload:sentToServer", (e, options) => {
    $(`img[data-id='${options.file.__guid__}']`).css({
      borderColor: 'yellow'
    });

  }).on("upload:success", (e, options) => {
    $(`img[data-id='${options.file.__guid__}']`).css({
      borderColor: "green"
    });

  }).on("upload:failure", (e, options) => {
    alert(`'${options.file.name}' upload failed; please retry`);
    $(`img[data-id='${options.file.__guid__}']`).remove();
  });

  $('.file-drop').jackUpDragAndDrop(jackUp);

  $(document).bind('drop dragover', e => {
     e.preventDefault();
  });

This works just as expected with one image upload button (classed as file-drop). However, a page will have an unknown number of these image upload buttons.

When there is more than one upload button, every time a file is added it's appended to all image-block-container elements, instead of just the one that was targeted. It appears that jackUp has no notion of the element that triggered it.


What's the best way to allow each upload button to know what called it? I've tried surrounding it in an .on('drop'... block. That gave me access to the element, but none of JackUp's events fired.

Any help or advice for a lightweight Rails-friendly ajax upload gem is appreciated!

Upvotes: 0

Views: 40

Answers (1)

pherris
pherris

Reputation: 17743

You are broadly matching multiple parts of your DOM with this query selector: $('[data-behavior=image-block-container]'). Multiple elements matching this selector are presumably the cause of your weird update issue.

If you want to target just the element that the user was interacting with, the e variable in the upload:imageRenderReady event handler should have a [target][1] which is generally what the user was interacting with and should get you close to what you want (depending on how your DOM is structured).

From jQuery:

The target property can be the element that registered for the event or a descendant of it.

Upvotes: 0

Related Questions