2
var objs = new Array();

function Foo(a) {
    this.a = a
    $("#test").append($("<button></button>").html("click").click(this.bar));
}

Foo.prototype.bar = function () {
    alert(this.a);  
}

$(document).ready(function () {
    for (var i = 0; i < 5; i++) {
        objs.push(new Foo(i));
    }
});

is it possible to make it so that when a button is clicked,

it returns corresponding Foo.a value (from Foo obj that created the button)?

1

3 Answers 3

3

The @Khnle's answer is close, but with that approach you need an anonymous function to use the self reference:

function Foo(a) {
  this.a = a;
  var self = this;
  $("#test").append($("<button></button>").html("click").click(function () {
    self.bar(); // correct `this` value inside `bar`
  }));
}

You can also use the $.proxy method, to preserve the object context:

function Foo(a) {
  this.a = a
  $("#test").append($("<button></button>")
            .html("click")
            .click($.proxy(this.bar, this)));
}

Check the above example here.

Sign up to request clarification or add additional context in comments.

Comments

1

Inside your click handler, this no longer refers to the Foo object, but the element where click takes place, which is the button element in this case. So one way to fix it is as follow:

function Foo(a) {
    this.a = a;
    var self = this;
    $("#test").append($("<button></button>").html("click").click(self.bar));
}

2 Comments

tried but does not work .. alert() in Foo.bar will only give me "undefined" where it should show Foo.a number of button's creator obj
It doesn't work because the $.click method receives only a reference to the self.bar function as an argument, and it will be executed with the this value pointing to the element that triggered the event.
0

Here's more jQuery style (no global objs or Foos)

   (function ($) {

       $.fn.aghragbumgh = function (settings) {
           var config = { 'a': 0 };

           if (settings) $.extend(config, settings);

           var bar = function () {
               alert(config.a);
           }

           this.each(function () {
               $(this).append($("<button></button>").html("click").click(bar));
           });

           return this;

       };

   })(jQuery);

    $(document).ready(function () {
        for (var i = 0; i < 5; i++) {
            $('#test').aghragbumgh({ 'a': i });
        };
    });      

Html:

<div id="test"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.