[英]jQuery plugin callback - jQuery Boilerplate
我正在为我的插件使用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);
我有一个错误,回调不是这个对象的方法。 有人可以帮忙吗?
重点放在如何特别是当你打电话给你的回调:
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
事件。 你不需要那么多...特别是因为如果你经常运行插件会导致滞后。 我建议连接事件监听器一次,并在触发事件后逐个调用所有回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.