开发者

jquery change operator "this" behaviour when handling events?

Please consider the following class. I'm beginning to use JQuery.

function AutoHide(elemControl, elemContent) {
  this.elemControl = elemControl;
  this.elemContent = elemContent;
  this.delay = 500;
  this.duration = 500;
  this.direction = 'vertical';
  this.effect = 'blind';

  function softHide()  {
    if ($(this.elemContent).is(':visible')) {
      $(this.ele开发者_高级运维mContent).delay(this.delay);
      $(this.elemContent).hide(this.effect, {direction: this.direction}, this.duration);
    }
    return this;
  };

  function softShow() {
    if ($(this.elemContent).is(':hidden'))
      $(this.elemContent).show(this.effect, {direction: this.direction}, this.duration);
    return this;
  };

  function setClickControl() {
    alert(this.elemControl);
    $(this.elemControl).click(softToggleVisibility);
  };

  this.softHide = softHide;
  this.softShow = softShow;
  this.setClickControl = setClickControl;

};

I have a global instance of the object AutoHide, and the methods softShow() and softHide() work like a charm (via Google Chrome's console). However, when I try to run the setClickControl() method, I realize that the operator "this" refers to an HTMLElement, and not to the class itself. Is this normal? I'm used to being able to consider the operator "this" a reference to the object i


You are correct. The hiding of the normal "this" object is the cause of a lot of confusion when first using jQuery. If you really need to make "this" act the way you're used to, use the jQuery proxy() API function:

http://api.jquery.com/jQuery.proxy/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜