Pedro Vinícius
Pedro Vinícius

Reputation: 496

How to trigger a jQuery UI custom event correctly?

I'm building a file uploader plugin for studying purposes, and I'm struggling trying to get my callback working the way I want to. Briefly, this widget opperates on an input field with the type file. A little of code to explain better:

$.widget('ultimatum.uploadify', {
  create: function() {
    // Irrelevant code here
  },

  _onChange: function(event) {
    // Private function that is fired when an "change" event
    // is triggered by the input.
    var files = event.target.files;
    var fileInfo = {};

    // When the file processing finish, I want to trigger this custom event:
    this._trigger("fileready", null, fileInfo);
  }
});

Ok, doing this way, I can handle the callback like so:

$('#upload-files').uploadify({
  fileready: function(event, file) {
    // My code here 
  }
});

The problem is that I want to handle this event like so:

$('#upload-files').uploadify();
$('.upload-files').on('fileready', function(event, file) {
  // My code here.
});

Although the former way works perfectly well, the latter doesn't. Is it possible to handle custom jQuery events this way, using "on"?

Upvotes: 1

Views: 1248

Answers (1)

Twisty
Twisty

Reputation: 30883

From http://api.jqueryui.com/jQuery.widget/

Events

All widgets have events associated with their various behaviors to notify you when the state is changing. For most widgets, when the events are triggered, the names are prefixed with the widget name and lowercased. For example, we can bind to progressbar's change event which is triggered whenever the value changes.

$( "#elem" ).bind( "progressbarchange", function() {`
  alert( "The value has changed!" );
});

Each event has a corresponding callback, which is exposed as an option. We can hook into progressbar's change callback instead of binding to the progressbarchange event, if we want to.

$( "#elem" ).progressbar({
  change: function() {
    alert( "The value has changed!" );
  }
});

All widgets have a create event which is triggered upon instantiation.

So for your widget, this would look like:

$('#upload-files').uploadify();
$('#upload-files').on('uploadifyfileready', function(event, file) {
  // My code here.
});

As I mentioned in the comment, I think that $('.upload-files') may be a typo, and that the proper selector is $('#upload-files').

Upvotes: 1

Related Questions