3

I tried to do a what described in https://api.drupal.org/comment/56868#comment-56868, but for Drupal 8.

Drupal.behaviors.corsFileAutoUpload = {
  attach: function (context) {
    $(context).find('input[type="file"].s3fs-cors-upload').once('auto-s3file-upload').on('uploadToS3', Drupal.s3fs_cors.uploadToS3);
    },
}

To invoke this from PHP, I used the following code.

$response->addCommand(new InvokeCommand($selector, 'uploadToS3');

But I got an error from core/misc/ajax.js line number of 1266, as the method for the element is not available. On inspecting eventlistener in Chrome, it was very well visible and I was also able to fire it from Browser Console. I am missing something here. How do we call a custom jQuery function using InvokeCommand?

2 Answers 2

3

In the JS side try with this:

(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

the PHP part looks ok to me.

-1

What's your selector, where you're trying to trigger the method ?? This won't be available according to your error. I guess you have an event/method mixup.

To trigger a custom event do something like:

new InvokeCommand('html', 'trigger', array(
  'your_bound_event',
  array('param1', 'param2'),
)));

And in your behavoir:

$(document).on('your_bound_event', function(ev, param1, param2) {
  console.log('hit');
});
2
  • The InvokeCommand object in your example is wrong. And is correct how Ankit used it.
    – Gnuget
    Commented May 23, 2017 at 21:40
  • 1
    It's not wrong .. it's a different approach. I'm triggering ("invoking") an event. You invoke a function.
    – rémy
    Commented May 24, 2017 at 6:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.