Question

I have a knockout script that loads the data from the server via ajax and outputs this information into the model. If to simplify everything, my model looks like this:

function ArticleViewModel() {
    var self = this;
    this.articleInfo = ko.observable();

    this.getArticle = function(id) { 
        $.get("/router.php", { articleId: id }, self.articleInfo, 'json');
    };
};

Everything works nicely (my view is populated with an information from the server). But what I need is to modify this information (for example change the data from timestamp to human readable format).

As I understood it, one way of achieving it is through knockout computed observables, but I do not see a reason of doing this because I will never need timestamp here and I can just change my data once after update and use it (if I am wrong, I would be happy to hear why and how to achieve what I want with computed observables).

So I am trying to change my data on ajax request in the following way (everything is the same, but ajax call has a callback):

$.get("/router.php", { type : 'mail' }, function(i){
    var d = new Date(i.date);
    self.articleInfo = {
        date: d.toString(),
        title: i.title
    };
}, 'json');

I have no errors on the page, but no information shows up. When I go to some other page, I see a warning: TypeError {stack: (...), message: "500 Error get /#Home Property 'articleInfo' of object #<ArticleViewModel> is not a function"}

What am I doing wrong?

Was it helpful?

Solution

I'm guessing that self.chosenMailData is an observable, and if it is you should be setting it as a function, i.e. self.chosenMailData(newValue); not as a property self.chosenMailData = newValue; //this will not work. If it is not observable, then, of course, any binding wouldn't be updated since they wouldn't know that the value has changed.

The reason is that if you replace the observable property (not the observable value) all subscriptions will still be to the old observable which still has the old value.

Regarding the error, it states 500 which makes it sound like a server error, not a client side error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top