开发者

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); 开发者_如何学Python 
}

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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜