KnockoutJS Update observableArray via AJAX-Collection of common programming errors

Been playing with KnockoutJS. Now, I am struggling to get my head around MVMM or whatever as I am not a programmer. However, I like the sounds of Knockout and I like the demos. So I have tried to create an observableArray (which, using jQuery templating lists the info on the page), and what I’d like to do is on button click (though ideally on page load) is run an ajax call and update the array.

Here is what I have but it isn’t working, it says “this.propertyDetails is undefined”

HTML:

Add property

JS:

var viewModel = {
propertyDetails: ko.observableArray([   
    {name: "1", type: "Unknown"},
    {name: "2", type: "Unknown"},
    {name: "3", type: "Unknown"},
    {name: "4", type: "Unknown"}
]),

addProperty: function() {
    //this.propertyDetails.push({name: "New Thing", type: "Unknown"});

    $.ajax({
        dataType: 'json',
        data: 'count=10',
        url: 'http://feeds.delicious.com/v2/json/tomleadbetter?callback=?',
        success: function (data) {
            $.each(data, function(i,item){
                console.log(item);
                this.propertyDetails.push({name: item.d , type: item.u});
            });
        }
    }); 
}

};

ko.applyBindings(viewModel);

It runs the ajax call on button click, but fails when trying to push each item into the array.

Don’t get me wrong, I may have got this completely incorrect! But this line work on button press to insert into the array

this.propertyDetails.push({name: “New Thing”, type: “Unknown”});

So any pointers would be great. Thanks

  1. You should work on your problem description. Fails completely isn’t very specific. Does it throw an error or does it run without error, but do nothing?

    My first guess is that this.propertyDetails doesn’t resolve because this isn’t what you think it is. You could try doing a console.log(this.propertyDetails) and see what happens. If it’s undefined then the this reference is the problem and you can fix it by adding .bind(viewModel) to your handler function.

    e.g.

    addProperty: function() {
        //this.propertyDetails.push({name: "New Thing", type: "Unknown"});
    
        $.ajax({
            dataType: 'json',
            data: 'count=10',
            url: 'http://feeds.delicious.com/v2/json/tomleadbetter?callback=?',
            success: function (data) {
                $.each(data, function(i,item){
                    console.log(item);
                    this.propertyDetails.push({name: item.d , type: item.u});
                }.bind(viewModel);
            }
        }); 
    }