3

I have a plugin that will open a modal every time a designated link is clicked. I attach the click event in the plugin's init() function, which then runs another of the plugin's functions.

The problem though is the plugin function called on click doesn't have access to other attributes of the plugin. It instead seems to be called within the scope of the window, not the plugin.

So in this example, toggleModal() has no access to this.config.container.

How do I trigger a plugin function on click, that stays within the plugin's scope?

The plugin is as below:

;(function($, window, document, undefined){

var Modal = function(elem, options){
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
    this.metadata = this.$elem.data('modal-options');
};

Modal.prototype = {
    defaults: {
        container: '#pageModal'
    },

    init: function() {
        this.config = $.extend({}, this.defaults, this.options, this.metadata);


        this.$elem.bind('click', this.toggleModal);

        if(!$(this.config.container).length) {
            this._build();
        }

        return this;
    },

    toggleModal: function() {
        $(this.config.container).fadeIn();
        return false;
    },

    _build: function() {
        var structure = '<section id="' + this.config.container.replace('#', '') + '"><section class="modalContent"></section></section>';

        $(structure).appendTo($('body')).hide();
    },
}

Modal.defaults = Modal.prototype.defaults;

$.fn.modal = function(options) {
    return this.each(function() {
        new Modal(this, options).init();
    });
};

})(jQuery, window, document);

1 Answer 1

1

It's not window, but the jQuery object you are binding to (as a product of what jQuery does). jQuery includes a helpful method called $.proxy to get around this:

this.$elem.on('click', $.proxy(this.toggleModal, this));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, works perfectly. Is there a better way to do this though? I'm not super familiar with making jQuery plugins, and I feel like rarely do I see $.proxy in other plugins. Is there a better way to be attaching click events to the elements supplied to a plugin?
@LucasRaines I don't see anything wrong with this method at all. Generally, plugin control is restricted to the plugin call (e.g. you would call $("element").modal('toggleModal', true) or something like that, but you can use whatever works for you and whoever you want to use your plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.