Daniele
Daniele

Reputation: 847

jQuery plugin boilerplate who's my this?

I'm playing with a real simple jQuery plugin "hello world" but I have some troubles with jQuery Plugin Boilerplate. Even if plain simple and well commented I feel like I'm missing a point, for instance, I get errors whatever jQuery method I use. Here's my init function.

    Plugin.prototype = {

    init: function() {

        console.log(this, this.element); // this.element return my element works fine

        this.element.on('click', function() { // 'undefined' is not a function :(
            alert('whoa'); 
        });

        this.element.click(function() {  // not working at all :'(
            alert('whoa'); 
        });

    },

    open: function(el, options) {
        // some logic
    }
};

Can you give me a hint?

Upvotes: 1

Views: 219

Answers (1)

gen_Eric
gen_Eric

Reputation: 227270

Since you are using a framework for making jQuery plugins, you're gonna have to follow their conventions.

If you were just doing $.fn.plugin = function(){}, then this would be a jQuery object, because $.fn is a reference to jQuery.prototype.

In your framework, this.element is the native DOM element, so to use jQuery methods, you need to wrap it in $().

$(this.element).on('click', function(){
});

Upvotes: 2

Related Questions