views:

135

answers:

2

I'm writing a little plugin for jQuery and so far I've got this:

(function($){

    $.fn.extend({

        someFunction: function() {
            return this.each(function() {
                var obj = $(this);
                obj.focus(someInternalFunction(obj));
            });
        }

    });

    function someInternalFunction(obj) {
    };

})(jQuery);

The problem is, when i attach someFunction to the object, the object gets focus and binding of someInternalFunction on focus event fails.

Then I tried to bind function to wrap the function call in the other function:

obj.focus(function() {
    someInternalFunction($(this));
});

This code works, but it isn't pretty at all. Is it possible to bind function on focus without wrapping it in the other function?

+1  A: 
$.fn.bindFocus() = function(){
    var internalFunction = function(){
        var $this = $(this),
            self = this;
        // try do stuff here
    };
    return this.each(function(){
        $(this).bind('focus', internalFunction);
    });
}

$('#myElement').bindFocus();

Hope it'll help ?

EDT. Sorry, first time get you wrong :)

Mushex Antaranian
Thanks, the bind() function works like a charm.
dmitriy
+1  A: 

Here:

obj.focus(someInternalFunction(obj));
                              ^^^^^

... you're calling the function, meaning that its return value is the thing that actually ends up being passed to focus(). Instead you want to pass a function to focus(). Given the fact that you want to pass obj to someInternalFunction, you'll have to define an additional function to wrap it all:

obj.focus(function(){
    someInternalFunction(obj);
});

Just to make things clear:

var x = function() { return 3; }; // Defining a function

x; // -> this is a function reference
x(); // -> this is 3
J-P
Oh... Well... Talk about embarrassing.Seriously, though, thanks for pointing out my mistake.Now I shall try to come up with a number of excuses on why I thought that a function call was equal to a function reference.
dmitriy