views:

43

answers:

3
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  A: 

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));
}
Khnle
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
andrew
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.
CMS
+2  A: 

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.

CMS
A: 

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>
Luc