2017-09-25 123 views
0

我正在为学习目的构建一个文件上传器插件,并且我努力让我的回调以我想要的方式工作。简而言之,这个小部件在类型为file的输入字段上运行。代码稍微更好地解释:如何正确触发jQuery UI自定义事件?

$.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); 
    } 
}); 

好吧,这样做的方式,我能处理像这样的回调:

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

的问题是,我想处理此事件,像这样:

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

尽管前一种方式工作得很好,但后者并没有。使用“on”可以以这种方式处理自定义jQuery事件吗?

+0

我看到'#'在一个选择器中,'.'在另一个选择器中。认为这是一个问题。 – Twisty

回答

0

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

活动

的所有部件都与他们的各种行为相关的事件时通知您的状态正在改变。对于大多数小部件,当触发事件时,名称会以小部件名称和小写字母作为前缀。例如,我们可以绑定到进度条的change事件,该事件在值更改时触发。

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

每一事件具有相应的回调,其被公开为一种选择。如果我们愿意,我们可以挂钩进度条的change回调,而不是绑定到progressbarchange事件。

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

所有的部件都被实例化时触发一个创建事件。

所以对你的部件,这将是这样的:

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

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

相关问题