首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery插件自定义事件触发器未触发

jQuery插件自定义事件触发器未触发
EN

Stack Overflow用户
提问于 2016-01-12 02:43:49
回答 1查看 917关注 0票数 0

我已经有一段时间没有做jQuery插件了,我正在开发一个带有选项和内部事件的非常常见的模板。在其中一个内部方法中,我需要触发一个自定义事件,以便其他页面可以捕获该事件并使用它。更具体地说,在这种用法中,在绘制canvas元素的末尾,我希望能够捕获插件外部的事件,以便捕获canvas内容,并将其发送到与插件本身无关的其他地方。

但是,看起来trigger调用并没有从另一个页面触发或查找绑定的事件。Firebug中未显示任何控制台消息。

以下是我的示例插件(简化版):

代码语言:javascript
复制
; (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中的单独页面绑定该事件:

代码语言:javascript
复制
$(".myPluginInstances").myPlugin().on("mydrawevent", function (e, data) {
    console.log("mydrawevent");
    console.log(data);
});

在Firebug中,我发现imgElement确实绑定了侦听器:

代码语言:javascript
复制
mydrawevent
    -> function(a)
        -> function(e, data)

我尝试过很多方法,比如在不同的DOM元素上调用trigger,将事件参数数据传入和传出数组,定义回调方法(这有其自身的问题),等等。我有一种感觉,这个问题很愚蠢,就在我面前,但我可以用更多的眼睛来仔细检查我的理智。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-12 05:09:36

作为我上面对Vikk的回应的进一步解释,问题确实是确定范围和了解哪些对象绑定到插件的哪些部分。在我的例子中,作为私有事件处理程序的内部方法被绑定到我的canvas元素,但是插件本身是在img元素上实例化的,这至少是这个特定实现的临时要求。

基于此,从内部事件处理程序中,使用$(this)意味着它试图在我的canvas元素上使用trigger,而不是从插件外部附加mydrawevent侦听器的img元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34728749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档