Reputation: 6826
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.
Upvotes: 3
Views: 291
Reputation: 15159
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>
Upvotes: 3
Reputation: 3308
You've defined "insert" as an object sitting on the jQuery object, instead of a function that can be called on a selection. I don't think you can ever get the scope of the current selection with it structured that way. You can call goodbye() successfully since it doesn't rely on any context/scope to execute.
Upvotes: 0