Björn
Björn

Reputation: 13207

Accessing instance from within prototype function other than through "this" possible?

var dups = new Dups($("#el"))

function Dups($el) {
 this.value = 23
 $el.on("click", this.onClick)
}

Dups.prototype.onClick = function(){
// usually "this" inside here refers to the instance (Dups)
// but because jquery changes "this", inside here "this" refers to the clicked element
// how can I access the Dups instances "this.value" from here?
   alert(this.value) // does not alert 23
}

My Problem is in the Dups.prototype.onClick function. Any ideas how to elegantly access the Dups instances "this" other than passing "this" (the clicked element) manually, so "this" in the prototype.onClick is the desired one, like so:

...
$el.on("click", function(){this.onClick(this)})
....

It works but I am wondering if there is a better way.

Upvotes: 0

Views: 187

Answers (2)

user1106925
user1106925

Reputation:

You can use jQuery.proxy to get a function that invokes your function with this bound to your object...

$el.on("click", $.proxy(this, 'onClick')

Upvotes: 1

mu is too short
mu is too short

Reputation: 434615

You can use $.proxy as a portable implementation of bind:

function Dups($el) {
    this.value = 23;
    $el.on("click", $.proxy(this.onClick, this));
}

$.proxy gives you a new function that executes with the specified this:

jQuery.proxy( function, context )
Returns: Function

Description: Takes a function and returns a new one that will always have a particular context.

The standard bind method on function objects does the same thing (and more) but isn't available everywhere.

Then you could get the clicked element through the passed event if you needed it:

Dups.prototype.onClick = function(event) {
    // event.target is what was clicked
}

Demo (open your console please): http://jsfiddle.net/ambiguous/K2BuX/

Upvotes: 1

Related Questions