2012-06-02 3 views
0

Je ne comprends pas comment passer une variable de la fonction init à la fonction bindEvent dans mon objet: Pour le moment, je suis indéfini.Variable non définie objet 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(); 

Comment passer correctement une variable d'une fonction à une autre dans un objet?

Merci!

Répondre

1

Vous pouvez le faire:

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

Le problème est que « ce » en vous gestionnaire n'a pas été l'instance de Fisheye, mais la fenêtre.

Mais vous aurez un problème similaire avec le toggleClick. Une solution pour ceux qui pourraient être de le faire:

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

Grand, je comprends! Merci – Chuck

0

rapidement que la structure, ajouter à la fonction param

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

sur la fonction init

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