管理 jQuery 插件上事件处理程序的范围



我正在使用jQuery的事件系统来允许外部代码驱动我的插件。在我的事件处理程序中,"this"设置为事件绑定到的元素,那么我访问插件方法本身的最佳方式是什么?

;(function($, window, document, undefined){
    var pluginName = "book";
    // Standard constructor
    function Plugin(element, options){
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this.init();
    }
    // Simple init
    Plugin.prototype.init = function(){
        this.setBindings();
    }
    // Tie local methods to event channels
    // so that external code can drive the plugin. 
    Plugin.prototype.setBindings = function(){
        var events = {
            'book-open'      : this.open,
            'book-next-page' : this.toNext,
            'book-prev-page' : this.toPrev,
            'book-cover'     : this.toFront,
            'book-back'      : this.toBack
        }
        for(event in events){
            var fn = events[event];
            console.log(event);
            this.$element.on(event, fn);
        }
    };
    // Event Handlers
    Plugin.prototype.open = function(){
        // when called externally 'this' refers
        // to the element the plugin was intialized on.
        // I want to be able to call the plugin's 'private'
        // methods, like someMethod() below.
    };
    /* .... other event handlers ...  */
    // 'Private' plugin methods
    Plugin.prototype.someMethod = function(){
        // do something
    }
    // Wrap and return technique from @ajpiano & @addyosmani
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if ( !$.data(this, "plugin_" + pluginName )) {
                $.data( this, "plugin_" + pluginName,
                    new Plugin( this, options ));
            }
        });
    }
 })(jQuery, window, document);

您可以调用一个函数,而不是传递函数本身,该函数将返回您要执行的函数,该函数是插件周围的闭包。

var createBookOpenFunction = function () {
    var self = this; //since you execute this function on the plugin, "this" will be the plugin
    return function () {
        self.open();
    }
};

然后,而不是打电话...

this.$element.on(event, fn);

你改为打电话

this.$element.on(event, this.createBookOpenFunction());

所以现在,当在$element上调用函数时,实际执行是在插件对象上完成的,因为它在"self"上是封闭的。
你可以通过返回的函数将参数(如果有的话)输入到调用"self.open()"中。

此外,此线程可能会有所帮助:控制 jQuery 事件中"this"的值

(我不直接使用 jQuery,所以我不熟悉 API 中可用的所有内容,但这里的一些帖子似乎有解决您问题的替代解决方案)

最新更新