andrew
andrew

Reputation: 23

jquery event function call with oop?

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)?

Upvotes: 2

Views: 1562

Answers (3)

Luc
Luc

Reputation: 1528

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>

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827198

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.

Upvotes: 3

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

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));
}

Upvotes: 1

Related Questions