我已经有一段时间没有做jQuery插件了,我正在开发一个带有选项和内部事件的非常常见的模板。在其中一个内部方法中,我需要触发一个自定义事件,以便其他页面可以捕获该事件并使用它。更具体地说,在这种用法中,在绘制canvas
元素的末尾,我希望能够捕获插件外部的事件,以便捕获canvas
内容,并将其发送到与插件本身无关的其他地方。
但是,看起来trigger
调用并没有从另一个页面触发或查找绑定的事件。Firebug中未显示任何控制台消息。
以下是我的示例插件(简化版):
; (function ($, window, document, undefined) {
"use strict";
var $canvas,
context,
defaults = {
capStyle: "round",
lineJoin: "round",
lineWidth: 5,
strokeStyle: "black"
},
imgElement,
options,
pluginName = "myPlugin";
function MyPlugin(element, opts) {
this.imgElement = element;
this.options = $.extend({}, defaults, opts);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(MyPlugin.prototype, {
init: function () {
var $imgElement = $(this.imgElement);
$canvas = $(document.createElement("canvas")).addClass("myPluginInstances");
$imgElement.after($canvas);
context = $canvas[0].getContext("2d");
$canvas.on("mousedown touchstart", inputStart);
$canvas.on("mousemove touchmove", inputMove);
$canvas.on("mouseup touchend", inputEnd);
}
});
$.fn.myPlugin = function (opts) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new MyPlugin(this, opts));
}
});
};
function inputStart(event) {
//...processing code
}
function inputMove(event) {
//...processing code
}
function inputEnd(event) {
//...processing code
// Trigger custom event
$(this.imgElement).trigger("mydrawevent", [this.toDataURL()]);
}
}(jQuery, window, document));
然后,从document.ready
中的单独页面绑定该事件:
$(".myPluginInstances").myPlugin().on("mydrawevent", function (e, data) {
console.log("mydrawevent");
console.log(data);
});
在Firebug中,我发现imgElement
确实绑定了侦听器:
mydrawevent
-> function(a)
-> function(e, data)
我尝试过很多方法,比如在不同的DOM元素上调用trigger
,将事件参数数据传入和传出数组,定义回调方法(这有其自身的问题),等等。我有一种感觉,这个问题很愚蠢,就在我面前,但我可以用更多的眼睛来仔细检查我的理智。
发布于 2016-01-12 05:09:36
作为我上面对Vikk的回应的进一步解释,问题确实是确定范围和了解哪些对象绑定到插件的哪些部分。在我的例子中,作为私有事件处理程序的内部方法被绑定到我的canvas
元素,但是插件本身是在img
元素上实例化的,这至少是这个特定实现的临时要求。
基于此,从内部事件处理程序中,使用$(this)
意味着它试图在我的canvas
元素上使用trigger
,而不是从插件外部附加mydrawevent
侦听器的img
元素。
https://stackoverflow.com/questions/34728749
复制相似问题