0

I am writing an easy web app using Knockout.js but I'm having a lot of trouble accomplishing something that should be easy but i can't figure out where I am wrong. I have a ko.observableArray and i fill it with JSON data from a php REST server. When I add or remove items from this array, the UI updates fine. I want the UI updated when I edit an array element too. I read that the array's element aren't observable, so I tried to make them Observable but still it doesn't work. Here's the code. (I omissed parts I don't consider important)

function sectionViewModel(){

    var self = this;
    self.sections = ko.observableArray();
            self.sectionToEdit = ko.observable();

        //code to initialize self.sections
    $.getJSON("sections", function(data){
         for(var i = 0; i < data.length ; i++){
             var id = ko.observable(data[i].id);
              var nome = ko.observable(data[i].nome);
             self.sections.push({id:id, nome:nome});
          }
     });



    self.confirmEdit = function(){
        $.ajax({
            url: 'sections/' + self.sectionToEdit().id,
            type: 'PUT',
            data: self.sectionToEdit().nome,
        });
    }

};

var debug = new sectionViewModel();
ko.applyBindings(debug);

This code works if I don't do the for inside $.getJSON but with it, I obtain the following error: Object [object global] has no method 'disposeCallback' from knockout.js in the moment i trigger the confirmEdit function. The PUT request it's not executed either and I have no idea why. Any help is really appreciated, thanks!

1 Answer 1

3

Because nome is an observable, you have to unwrap it in your function:

self.confirmEdit = function(){
    $.ajax({
        url: 'sections/' + self.sectionToEdit().id,
        type: 'PUT',
        data: self.sectionToEdit().nome(),
    });
}

Otherwise, jQuery treats the observable as an object map, including calling all functions on the object.

Sign up to request clarification or add additional context in comments.

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.