0

I want to pass the currently called object with it's currently set parameters on to a closure function. I'm not sure how to do this in general, but then I think jQuery adds another layer of confusion because this refers to an element.

Example:

jQuery Plugin

(function( $ ){
  $.fn.addContentType = function(obj) {
    var name = "this is just an example";
    obj.func.call(this); //<--I want to pass this object, not the jQuery selector   
  };
})( jQuery );

Call to Plugin

jQuery("#someelement").addContentType({
  func:function(){
    console.log(this.name); //<--Expect "this is just an example"
  }
});

Any ideas how to do this?

This is just an example and doesn't do anything, I'm just trying to show what I'm after. If I am missing details, let me know.

Senica Gonzalez
  • 7,996
  • 16
  • 66
  • 108
  • 1
    You can't get local variables. – SLaks Dec 18 '11 at 19:14
  • `name` is just a local variable inside `addContentType`. `this` on the other hand refers to all elements selected by `jQuery("#someelement")`. Hence, `this.name` is the same as `jQuery("#someelement").name`. – Felix Kling Dec 18 '11 at 19:14
  • @Felix: Correct. I mentioned that in the beginning. I was asking if there was a way to pass a "this" that would refer to the object itself – Senica Gonzalez Dec 18 '11 at 19:18
  • Which object to you mean? The selected element? Or the jQuery object? What if multiple elements are selected? – Felix Kling Dec 18 '11 at 19:21

3 Answers3

1

You can use .apply() to pass both context and arguments from the original function call:

obj.func.apply(this, arguments);

MDN reference for .apply() and MDN reference for the arguments object.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

To access name as a property of the jQuery object, you'd need to add it instead of using a variable.

this.name = "this is just an example";
obj.func.call(this);

Or use the variable to pass the value to the function:

var name = "this is just an example";
obj.func.call(this, name);

and receive it on the other end:

func:function( name ){
   console.log( name ); //<--Expect "this is just an example"
}

Or to make your obj the this value, do this:

obj.func.call(obj, name);

...but you still need to pass the argument unless you assign the value as a property to obj.

RightSaidFred
  • 11,209
  • 35
  • 35
0

You get DOM element from jQuery selector like this:

$("#elem").get(0);

or

$("#elem")[0];

Read this for detailed info (if you need it)

Community
  • 1
  • 1
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367