2012-06-02 4 views
0

init 함수의 변수를 내 객체의 bindEvent 함수에 전달하는 방법을 모르겠습니다. 현재로서는 정의되지 않습니다.정의되지 않은 변수 jQuery 객체

var Fisheye = { 
    init: function() { 

     $('body').hide(); 

     $(window).load(function() { 
      $('body').fadeIn('slow'); 

      this.imgs = $('.pic').children('img'); 
      this.originalWidth = $(imgs).first().css('width'); 
      this.minWidth = 300; 

      imgs.width(300); 

      Fisheye.bindEvents(); 

     }); 

    }, 

    bindEvents: function() { 
     $(this.imgs).toggle(this.toggleClick, this.toggleClick); 
     console.log(this.imgs); // Why do I get Undefined here? 
    }, 

    toggleClick: function() { 
     //Todo 
    } 
} 


Fisheye.init(); 

변수를 함수에서 다른 변수로 올바르게 전달하는 방법은 무엇입니까?

감사합니다.

답변

1

이 작업을 수행 할 수 있습니다

var Fisheye = { 

    init: function() { 
     var _this = this; 
     $('body').hide(); 
     $(window).load(function() { 
      $('body').fadeIn('slow'); 
      _this.imgs = $('.pic').children('img'); 
      _this.originalWidth = $(_this.imgs).first().css('width'); 
      _this.minWidth = 300; 
      _this.imgs.width(300); 
      _this.bindEvents(); 
     }); 

    }, 

    bindEvents: function() { 
     $(this.imgs).toggle(this.toggleClick, this.toggleClick); 
    }, 

    toggleClick: function() { 
     //Todo 
    } 
} 


Fisheye.init(); 

문제는이 "이"당신 핸들러에 어안하지만 윈도우의 인스턴스 아니었다는 것이다.

하지만 toggleClick에서 비슷한 문제가 발생합니다. 사람들을위한 해결책이 할 수 : 빠르게 단지 구조

bindEvents: function() { 
    var _this = this; 
    var toggleFunction = function(){_this.toggleClick()}; 
    $(this.imgs).toggle(toggleFunction, toggleFunction); 
}, 
+0

위대한 init 함수의 기능

bindEvents: function(imgs) { $(imgs).toggle(this.toggleClick, this.toggleClick); console.log(imgs); // Why do I get Undefined here? },... 

에 PARAM를 추가, 이해! 감사 – Chuck

0

... 
var imgs = .. 
Fisheye.bindEvents(imgs);