简体   繁体   English

jQuery事件函数调用与oop?

[英]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)? 它返回相应的Foo.a值(来自创建按钮的Foo obj)?

The @Khnle 's answer is close, but with that approach you need an anonymous function to use the self reference: @Khnle的答案很接近,但是使用这种方法,您需要一个匿名函数来使用self引用:

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: 您还可以使用$.proxy方法来保留对象上下文:

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. 在单击处理程序内部,它不再引用Foo对象,而是单击发生的元素,在这种情况下为button元素。 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) 这是更多的jQuery样式(没有全局objs或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: HTML:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM