user686483
user686483

Reputation: 1506

knockoutjs - Computed Observable returns error

I'm retuning a JSON object from a web service and using knockout 2.01 to display the results. I'm able to display my results without an issue but as soon as I try to add a computed observable into the view model I get the error below.

What am I missing with this code below?

Uncaught TypeError: Object # has no method 'dateCreated'

!--- JSON

{"jobTitle":"Digital designer","dateCreated":"7/7/2012","timeCreated":"2:27    PM","location":"Perth","jobSummary":"one\ntwo\nthree","Uri":"/candidates/view-all-jobs/digital-designer/","CreateDate":"\/Date(1341635236000)\/"}

!-- html

<div data-bind="foreach: $data">
 <article>
    <header>
      <time datetime="2007-08-29T13:58Z"></time>
      <h3><a target="_self" data-bind="text: $data.location"> </a> </h3>
    </header>
    <span data-bind="text: $data.fullDate">  </span> </article>
 </div> 

!-- code

var viewModel = ko.observableArray();

$(document).ready(function () {
    if ($('#featured-jobs').length > 0) {
        $.ajax({

            type: 'POST',

            url: "handler/jobServer.ashx",

            data: { 'jobType': '1' },

            success: OnComplete,

            error: OnFail,

            dataType: 'json'
        });
    }
});



function OnComplete(result) {

    var self = this;
    ko.mapping.fromJS(result, {}, viewModel);

    self.fullDate = ko.computed(
  function () {
     return self.dateCreated() + " " + self.timeCreated();
  }, self); 

    ko.applyBindings(new viewModel());

}

function OnFail(result) {

    alert('Request Failed');

}

Upvotes: 0

Views: 513

Answers (1)

Arbiter
Arbiter

Reputation: 1024

It's because onComplete creates a new object called self which doesn't have a dateCreated Property. I think what you really want is to add that computed observable to every item in that viewModel.

Edit:

Observables are awesome, but sometimes they’re not the answer (especially if a value is not likely to change, like I suspect is the case for “created date” and “created time”). Here’s how I would do it (without observables). Note, you can still bind to non-observable properties:

function OnComplete(result) {

    for (var i = 0; i < result.length; i++)
    {
        result[i].fullDate = result[i].dateCreated + " " + result[i].timeCreated;
    }

    viewModel(result);
    ko.applyBindings(viewModel);
}

If I'm wrong, and the user will be manipulating these values, you can do it like this (with observables):

function OnComplete(result) {

    ko.mapping.fromJS(result, {}, viewModel);

    for (var i = 0; i < viewModel.length; i++)
    {
        viewModel[i].fullDate = ko.computed(
            function () {
                return this.dateCreated() + " " + this.timeCreated();
            }, viewModel[i]); 
    }

    ko.applyBindings(viewModel);
}

Upvotes: 1

Related Questions