Clipboard.js: Should the library have a beforeAction handler?

Created on 14 Nov 2016  路  7Comments  路  Source: zenorocha/clipboard.js

What it should do?

The lib should be able to execute a function that would allow it (or not) to proceed with the predefined action;

Why it is useful?

If the copy button is used as a premium feature of an application, this handler would allow developers to prevent users that doesnt have permission to do that action;

How users should use it?

//client.js
const handler = () => {
  // loading state?
  return fetch(`/user/has-feature/${featureName}`)
};
new Clipboard(selector, { beforeAction: handler });

// ----------------------------
// clipboard.js#L44
{
// ...
  onClick(e) {
    // ...
    this.beforeAction().then(() => {
      this.clipboardAction = new ClipboardAction({
        action  : this.action(trigger),
        target  : this.target(trigger),
        text    : this.text(trigger),
        trigger : trigger,
        emitter : this
      });
    })
  }
}
new feature

Most helpful comment

This is a very important use case, specially for users who want to execute async tasks before copying. Next year I'll start playing with the idea of having a promise-based API, so let's keep this on hold for now.

All 7 comments

This is a very important use case, specially for users who want to execute async tasks before copying. Next year I'll start playing with the idea of having a promise-based API, so let's keep this on hold for now.

Why not beforeCopy instead of beforeAction?
It reveals intention
new Clipboard(selector, { beforeCopy: asyncMethod }); better than new Clipboard(selector, { beforeAction: asyncMethod });

@guillaumevincent, I agree that it reveals intention but, and the cut action? Do you think that we have to do two or three handlers? Like beforeCopy, beforeCut and beforeWhatever (I can't think in a cool name for the last).

@pedroramon you are right, 2/3 handlers is not a good idea, so beforeAction is better because more generic.

This is huge for me as I need to copy the window.location.href after the hash has changed. (on button click of course)

@zenorocha that "promise" use is that I was looking for. Just an Ajax request before setting text :)

Thanks for kicking out Flash!

Looks like this will not be possible because document.execCommand('copy') doesn't work asynchronously in some browsers as pointed out by @guillaumevincent on #338. See http://hansifer.com/clipboardCopyTest.html

Was this page helpful?
0 / 5 - 0 ratings