jQuery插件回调-jQuery Boilerplate

jQuery plugin callback - jQuery Boilerplate

本文关键字:Boilerplate -jQuery 回调 插件 jQuery      更新时间:2023-09-26

我的插件使用的是jquery样板模板。我需要从这个插件中提供一些回调。这个回调需要是一些带有偏移坐标的变量。

var coordinates = {
    x: x2, y: y2
};

我试着这样委托这个回调:

;(function ($, window, document) {
/* 'use strict'; */
// default options
var name = "plugin",
    defaults = {};
// constructor
function plugin (options, callback) {
    this.settings = $.extend({}, defaults, options);
    this.init();
    this.callback = callback;
}
plugin.prototype = {
    init: function () {
        var offset = $(this).offset(),
            x2 = (e.pageX - offset.left),
            y2 = (e.pageY - offset.top);
        $(document).on('mouseup', function() {
            var coordinates = {
                x: x2, y: y2
            };
            this.callback(coordinates);
        });
    }
};
// initialize
$.fn[name] = function (options, callback) {
    return this.each(function() {
        if (!$.data(this, "plugin_" + name)) {
            $.data(this, "plugin_" + name, new plugin(options, callback));
        }
    });
};
})(jQuery, window, document);

我有一个arror,回调不是这个对象的方法。有人能帮忙吗?

关注如何,尤其是在哪里调用回调:

plugin.prototype = {
    init: function () {
        var offset = $(this).offset(),
            x2 = (e.pageX - offset.left),
            y2 = (e.pageY - offset.top);
        $(document).on('mouseup', function() {
            var coordinates = {
                x: x2, y: y2
            };
            this.callback(coordinates);
        });
    }
};

您正在创建匿名嵌套函数。默认情况下,匿名函数具有this === window


编辑:感谢KevinB的评论,我注意到我之前的声明并不是适用于所有情况,只是因为可以通过调用.apply().call()来更改函数的上下文,jQuery这样做是为了让您可以简单地使用$(this)来访问触发事件的元素。

我想的是,如果在没有这两个方法的情况下调用匿名函数,那么它们就是this === window。但对于直接作为函数而不是方法调用的方法也是如此。以下内容也不起作用。

var obj = { foo : 'foo', bar : function(){console.log(this.foo);} };
$(document).on('mouseup', obj.bar);

首先是因为jQuery在调用回调时对上下文进行了上述更改,其次是因为一个简单的经验法则:上下文是点左侧的任何内容。当调用这样的回调:callback()时,点的左边没有任何东西,即不存在的this === null(不要打我),因此它默认为this === window


解决这个问题相当简单:只需引入一个引用插件实例的新变量。这个变量通常被称为that。微小的改变应该可以实现你的目标:

init: function() {
    var offset = $(this).offset(),
        x2 = (e.pageX - offset.left),
        y2 = (e.pageY - offset.top),
        that = this;
    $(document).on('mouseup', function(){
        var coordinates = {
            x: x2, y: y2
        };
        that.callback(coordinates);
    });
}

但要注意:按照插件当前的工作方式,每次运行时,它都会在mouseup事件上附加一个侦听器。你不需要那么多。。。尤其是因为如果你经常运行插件,会导致滞后。我建议将事件侦听器连接一次,并在事件触发后逐个调用所有回调。