简体   繁体   中英

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.

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.

只需猜测:因为您在声明变量之前就访问了它?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM