[jQuery] Re: Binding "this" inside anonymous functions

2007-12-19 Thread Byron

Just to clarify apply is a native javascript function implemented in
1.3
the second parameter isnt actually needed (its for defining arguments)

anyway i decided to jquerify it and ended with this:

(function ($) {
  $.extend($.fn, {
apply :function (fn, args) {
  return this.each(function () {
fn.apply(this, args);
  });
}
  });
})(jQuery);

now it can be called like so:

$('#example').apply(function () {
  alert(this.id);
});

$('#example').apply(function (a, b) {
  alert(a + " : " + b); // "foo : bar"
}, ['foo', 'bar']);


[jQuery] Re: Binding "this" inside anonymous functions

2007-12-18 Thread Byron

you can use apply()

example :

var el = $('#myDiv')[0];
var myFunc = function () {
  console.log(this);
};

myFunc.apply(el, [{type : "",  target : el}]);

i stumbled on this when looking through the trigger function.

probably not the best use of it, however i though it might be usefull.

-Byron


[jQuery] Re: Binding "this" inside anonymous functions

2007-12-18 Thread Joel Stein

Thanks, Jonathan.


[jQuery] Re: Binding "this" inside anonymous functions

2007-12-18 Thread Jonathan Sharp
It's a best practice to use var a = this to avoid the scope leak that you
mentioned.

Cheers,
-Jonathan


On 12/18/07, Joel Stein <[EMAIL PROTECTED]> wrote:
>
>
> > Also you might want to do "var a = this" so that it doesn't conflict
> with any global variables.
>
> Thanks, Josh.  That's what I suspected.  As far as the "var a =
> this"... is that because using "var" to declare the variable makes its
> scope within the function alone, or is the "var" unnecessary?
>


[jQuery] Re: Binding "this" inside anonymous functions

2007-12-18 Thread Joel Stein

> Also you might want to do "var a = this" so that it doesn't conflict with any 
> global variables.

Thanks, Josh.  That's what I suspected.  As far as the "var a =
this"... is that because using "var" to declare the variable makes its
scope within the function alone, or is the "var" unnecessary?


[jQuery] Re: Binding "this" inside anonymous functions

2007-12-17 Thread Josh Nathanson



I know I can use the following, and it will work, but is there
something similar in jQuery that's already available?



$('a').click(function() {
 a = this;
 $.ajax({
   url: this.href,
   success: function(data) {
 alert(a.href);
   }
 })
});



That's the way people do it in jQuery, although often people will use the 
variable "self" or "that".  AFAIK there isn't a specific method in jQuery to 
do what you are referring to.  Also you might want to do "var a = this" so 
that it doesn't conflict with any global variables.


-- Josh