[英]jQuery plugin custom event trigger not firing
自從我完成了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
的單獨頁面准備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
,將事件參數數據傳入和傳出數組,改為定義回調方法(這有其自身的問題)等。 我感覺到問題出在我面前,有點愚蠢,但是我可以用更多的眼睛仔細檢查我的理智。
作為對我對Vikk的回應的進一步解釋,問題的確是確定范圍並了解哪些對象綁定到插件的哪些部分。 就我而言,作為私有事件處理程序的內部方法已綁定到我的canvas
元素,但是插件本身已在img
元素上實例化,這至少是此特定實現的臨時要求。
基於此,從內部事件處理程序中使用$(this)
意味着它正在嘗試在我的canvas
元素上使用trigger
,而不是從插件外部將mydrawevent
偵聽器附加到其上的img
元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.