Jamie Hutber
Jamie Hutber

Reputation: 28074

Javascript scope issue - variable is undefined

I am slightly confused by this, as i am sure that all variables are taken to the 'top' of the javascript before run time and then processed from there.

So my error

 TypeError: hutber.portfolio.ko is undefined
 [Break On This Error]  
 items: ko.observableArray(hutber.portfolio.ko.data),

Object

(function ($) {
"use strict"; //For good development standards :)
hutber.portfolio = {
    init: function(){
        e(typeof(hutber));
        hutber.portfolio.changeOptionsBoxHeight();
        //Bind the height resize in window resize
        $(window).resize(function(){
            hutber.portfolio.changeOptionsBoxHeight();
        });
        //start KO
        hutber.portfolio.ko.init();
    },
    changeOptionsBoxHeight: function(){
        var height = $(window).height();
        $('.portfolio--options').height(height-400);
    }
};
hutber.portfolio.ko = {
    init: function(){
        ko.applyBindings(new hutber.portfolio.ko.portfolioViewModel());
    },
    data: [],
    items: ko.observableArray(hutber.portfolio.ko.data),
    portfolioViewModel: function(){

        hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

        $.getJSON('/js/pages/portfolio.json').done(function(info){
            hutber.portfolio.ko.data = info;
            hutber.portfolio.ko.items (hutber.portfolio.ko.data);
        });
    }
};
hutber.portfolio.init();
})(jQuery);

I really wanted to upload this to a fiddle but for some reason, i'm getting js errors on their site. I believe my firewall is blocking certain files from loading.

Upvotes: 0

Views: 773

Answers (2)

Amberlamps
Amberlamps

Reputation: 40448

At the point ko.observableArray(hutber.portfolio.ko.data) is run, hutber.portfolio.ko has not be defined yet.

You can work around it like that:

hutber.portfolio.ko = {
    init: function(){
        ko.applyBindings(new hutber.portfolio.ko.portfolioViewModel());
    },
    data: [],
    portfolioViewModel: function(){

        hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

        $.getJSON('/js/pages/portfolio.json').done(function(info){
            hutber.portfolio.ko.data = info;
            hutber.portfolio.ko.items (hutber.portfolio.ko.data);
        });
    }
};

hutber.portfolio.ko.items = ko.observableArray(hutber.portfolio.ko.data);

But at this point hutber.portfolio.ko.data is always []. So you might as well put ko.observableArray([]) in your original code.

Upvotes: 1

Roman
Roman

Reputation: 504

Just guess: Because you accessing variable before you declare it?

Upvotes: 0

Related Questions