0

我正在为我的插件使用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);

我有一个错误,回调不是这个对象的方法。有人可以帮忙吗?

4

1 回答 1

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

于 2013-11-20T22:33:45.863 回答