Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give jQuery plugin access to selected DOM objects

I'm experimenting with writing a plugin for jQuery that doesn't follow the pattern outlined int his document: http://docs.jquery.com/Plugins/Authoring

It is as follows:

(function( $ ){

$.fn.insert = {
    'hello': function(text){ 
        $(this).text(text); 
    },
    'goodbye': function(){
        alert('goodbye');
    }
}
})( jQuery );

The page instantiates this plugin with this code:

$(document).ready( function(){
    $('#test').insert.goodbye();
    $('#test').insert.hello('blahblahblah');
});

In this form, .goodbye() does initializes correct, but as is probably obvious, .hello() does not. On inspecting the this in firebug, it shows the scope to belong to its containing function. (cue facepalm).

How do I give the function inside 'hello' access to the selected DOM objects? I'm not really interested in having a discussion as to why or why not one should create a plugin in this fashion. It's more an academic exercise for me.

P.S. I should also note that I get this error when the hello() portion attempts to run: doc.createDocumentFragment is not a function.

UPDATE

(function( $ ){

$.fn.insert = {
    'el': this,
    'hello': function(text){ 
        $(this.el).text(text); 
    },
    'goodbye': function(){
        alert('goodbye');
    }
}

})( jQuery );

Made this update to the code. FYI, Firebug does show that this.el references the DOM object in question, and text is still carrying the passed string, but it's still not inserting the text into the element, and still giving me the aforementioned error.

like image 557
dclowd9901 Avatar asked Feb 03 '26 20:02

dclowd9901


1 Answers

I'm not sure... but this works:

<html>

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script>

            (function($){

                $.fn.myinsert = function(){

                    this.hello = function(text){ 
                        $(this).text(text);
                    };

                    this.goodbye = function(){
                        alert('goodbye');
                    };

                    return this; //this is the gotcha

                };

            })(jQuery);

            $(function(){
                var test = $('#test');
                test.myinsert().goodbye(); 
                test.myinsert().hello('heyo');
            });

        </script>
    </head>

    <body>

        <div id="test">My name is</div>

    </body>

</html>
like image 55
Homer6 Avatar answered Feb 06 '26 11:02

Homer6