简体   繁体   English

如何正确触发jQuery UI自定义事件?

[英]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 . 简而言之,此小部件在类型为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"? 是否可以使用“ on”以这种方式处理自定义jQuery事件?

From http://api.jqueryui.com/jQuery.widget/ 来自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. 例如,我们可以绑定到progressbar的change事件,该事件在值更改时触发。

$( "#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. 如果需要,我们可以挂钩到progressbar的change回调中,而不是绑定到progressbarchange事件。

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

All widgets have a create event which is triggered upon instantiation. 所有小部件都有一个create事件,该事件在实例化时触发。

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') . 正如我在评论中提到的,我认为$('.upload-files')可能是一个错字,而正确的选择器是$('#upload-files')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM