Tyler
Tyler

Reputation: 2639

How can I access an object instance's context from within a predefined function passed to the "bind" method invoked on the instance?

I have this snippet:

var test_img = $("<img />");
test_img.attr("src", img_url);
test_img.unbind("load");

console.log(test_img);

test_img.bind("load", function ()
    {
        console.log(this);
    });

The first console.log outputs:

[img]
    0: img  // expandable
    length: 1
    __proto__: Object[0]  // expandable

The second console.log outputs:

<img src=​"/​images/​Tree.jpg">​

Why are the two outputs different?

Also, I need to define the function that gets passed to test_img.bind elsewhere. I.e.,

function predefined_function()
{
    console.log(new_this);
}

var test_img = $("<img />");
test_img.attr("src", img_url);
test_img.unbind("load");

console.log(test_img);

test_img.bind("load", predefined_function);

How can I make it so that new_this is the same as this in the original snippet?

Upvotes: 1

Views: 50

Answers (2)

MarcChan
MarcChan

Reputation: 1

See this example:

https://jsfiddle.net/y89zk2k8/1/

var textDiv = $("<div />").append("click me :)"),
    func = function() {
        var $me = $(this);
    console.log($me);
    };

textDiv.off("click");

console.log(textDiv);

textDiv.on("click", func);

$("body").append(textDiv);
  1. To make new_this same as this: You need to change it to the Jquery Oject in the event response function.

  2. Define the function that gets passed to the event elsewhere: Pass the function as param to the event response function.

  3. Use .on to replace .bind, because .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

Upvotes: 0

user6586783
user6586783

Reputation:

As an answer to your first question, the difference is because the constructor of the first output is jQuery.fn.init, but the constructor of the second output is HTMLImageElement. You can access image from first output using test_img[0].
If you want to use some predefined function, just replace new_this with this.

Upvotes: 2

Related Questions