-1

I don't understand how to pass a variable from the init function to the bindEvent function in my object: At the moment, I get undefined.

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

How to properly pass a variable from a function to another in an object?

Thanks!

0

2 Answers 2

1

You can do this :

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

The problem is that the "this" in you handler wasn't the instance of Fisheye but the window.

But you'll have a similar problem with the toggleClick. A solution for those could be to do this :

bindEvents: function() {
    var _this = this;
    var toggleFunction = function(){_this.toggleClick()};
    $(this.imgs).toggle(toggleFunction, toggleFunction);
},
Sign up to request clarification or add additional context in comments.

Comments

0

rapidly just the structure , add param to the function

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

on init function

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.