jQuery插件回调 - jQuery Boilerplate

时间:2013-11-20 21:40:09

标签: javascript jquery plugins boilerplatejs

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

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);

我对回调不是此对象的方法感到恐惧。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

关注如何,尤其是哪里,您可以调用回调:

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事件上附加一个侦听器。你不需要那么多...特别是因为如果你经常运行插件会导致滞后。我建议连接事件监听器一次,并在触发事件后逐个调用所有回调。