1

Can't load my JSON data into ko.observableArray and have no clue why.

$(document).ready(function(){
    function Region(uid, name) {
        this.uid = ko.observable(uid);
        this.name = ko.observable(name);
    }

    function CompanyViewModel() {
        this.regions = ko.observableArray([]);
    }

    ko.applyBindings(new CompanyViewModel());   

    // Init.
    $.getJSON( '/regions/', 
        function(data){
            if(data.status == 'ok')
            {
                var mappedData = ko.utils.arrayMap(data.regions, function(item) {
                    return new Region(item.uid, item.name);
                });
                CompanyViewModel.regions( mappedData );
            }
        }
    );
});

Debugger says: Uncaught TypeError: Object function CompanyViewModel()... has no method 'regions'

I'm new to Knockout and sure there is some obvious error, but i don't know where.

0

1 Answer 1

3

Haven't tested it, but should give you an idea on what I mean, this is how I would do it:

$(document).ready(function(){
    var Region = function(uid, name) {
        this.uid = ko.observable(uid);
        this.name = ko.observable(name);
    }

    var CompanyViewModel = function() {
        this.regions = ko.observableArray([]);
    }

    var model = new CompanyViewModel();
    ko.applyBindings(model);   

    // Init.
    $.getJSON( '/regions/', 
        function(data){
            if(data.status == 'ok')
            {
                var mappedData = ko.utils.arrayMap(data.regions, function(item) {
                    return new Region(item.uid, item.name);
                });
                model.regions( mappedData );
            }
        }
    );
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I hope now i understand my error. I have created "anonymous" viewmodel object and tried to invoke method from model definition itself, not from object, right?
Right, you were not working on the instance of the model. By the way, if you don't plan on changing a property (say an ID), there's no reason to make it into an observable.

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.