views:

73

answers:

2

I have the following jQuery function (simplified):

function doSomething(el, str) {
 el.find('.class').text(str));
}

Don't worry about the .text() part, in reality I'm doing something a bit more complicated than that... But since that's irrelevant to my question, I'm just using .text() here as a simple example.

The problem is, everytime I'm calling the doSomething() function, the code looks like this:

doSomething($(this), foo); // the second argument is irrelevant
doSomething($(this), bar); // the second argument is irrelevant

As you can see, I'm always passing $(this) as the first argument. Somehow I feel this is not the way to go... Can this function be improved so it automatically inherits the $(this) from the context where it's called? Maybe something like the following:

$(this).doSomething(foo); // the foo argument is irrelevant
$(this).doSomething(bar); // the bar argument is irrelevant
+1  A: 

seems you want something that works like jquery plugin.

(function($){

//Attach doSomething method to jQuery
$.fn.extend({ 

      doSomething: function(options) {

        return this.each(function() {

          var el = $(this);
          // do something here

        });
    }
});

})(jQuery);
Anwar Chandra
+2  A: 

You can create a simple plugin to do this.

Lots of articles about. See this one on the jQuery site for more info

$(function(){

   jQuery.fn.changeAnchorText = function(str) {
     return this.each( function(){
        $(this).find('a.someClass').text(str);
     });
   };

});

then to invoke it

$('div').changeAnchorText("Any descendant anchor tags inside this div with a class of someClass will have the text changed to this message");
redsquare
What's `changeAnchorText()`? ;-)
Tomalak
@Tomalek: an example for "doSomething".
Thilo
it looks that way yeah...
redsquare