从事件处理程序访问私有属性和方法

时间:2014-07-04 18:52:57

标签: javascript jquery

我已使用jQuery Boilerplate模板作为jQuery插件的起点。此模板提供了一个设置,其中this表示插件实例,并提供对属性和方法的访问:

init: function() {
    $(this.element).css({borderColor: "red"});
    this.drawMarker([100, 200]);
},
drawMarker: function(coordinates) {
    if (this.settings.isAbsolute) {
        // ...
    }
}

现在我需要处理一些鼠标点击,这一切都让人感到困惑,因为回调函数重新定义了this变量来表示点击的事件,所以,为了访问插件的东西,我走了过来这个丑陋的解决方法:

this.container.on("click", "." + this.settings.markerClass,
        {plugin: this}, this.removeMarker);

......和:

removeMarker: function(event){
    var plugin = event.data.plugin;
    var marker = $(this);
    if (plugin.settings.isAbsolute) {
        // ...
    }
}

这实际上是我应该做的,还是我忽略了一种最直接的方法?

2 个答案:

答案 0 :(得分:0)

如果您需要访问私有范围的变量(使用因此定义不在插件prototype上的函数),只需创建一个别名插件对象的附加变量:

var plugin = this;

this.container.on('click', function() {
    // use plugin here
    ...
});

如果有问题的回调函数在原型上,则可以访问回调中的对象:

var plugin = $(element).data('plugin_' + pluginName);

答案 1 :(得分:0)

一种可能性是使用jQuery.proxy()函数(在1.4上添加)强制在事件处理程序中使用给定的上下文:

this.$container.on("click", "." + this.settings.markerClass,
    $.proxy(this.removeMarker, this));

然后,您可以按以下方式联系到您需要的东西:

removeMarker: function(event){
    var $marker = $(event.target);
    if (this.settings.isAbsolute) {
        // ...
    }
}

此技术由Patrick Evans提供。

相关问题