Martin
Martin

Reputation: 11336

How to refactor this javascript code for many instantiates

I have the following code to upload a profile photo which is working fine. I have also many different cases (upload favicon, logo, etc) which may end up with a lot of repetition.

var myDropzone;

myDropzone = new Dropzone("div#profilePhoto", {
  url: "/attachments",
  paramName: "attachment[file]"
});

myDropzone.on("sending", function(file, xhr) {
  return $.rails.CSRFProtection(xhr);
});

My question is how can I refactor this code to be as generic as possible yet allow me to pass specifics options (url, paramName, etc) depending on its ID?

Upvotes: 0

Views: 54

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

We don't know much about the context where you're using that, but I believe something like this function could work:

function createDropzone(selector, url, paramName) {
    var myDropzone = new Dropzone(selector, {
      url: url,
      paramName: paramName
    });

    myDropzone.on("sending", function(file, xhr) {
      return $.rails.CSRFProtection(xhr);
    });
}

You would call it like this:

createDropzone("div#profilePhoto", "/attachments", "attachment[file]");

Upvotes: 4

Related Questions