0

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');

}
4

1 回答 1

1

这是因为 onComplete 创建了一个名为的新对象self,它没有dateCreated属性。我认为你真正想要的是将计算的 observable 添加到viewModel.

编辑:

Observables 很棒,但有时它们不是答案(特别是如果一个值不太可能改变,就像我怀疑“创建日期”和“创建时间”的情况一样)。这就是我的做法(没有可观察的)。请注意,您仍然可以绑定到不可观察的属性

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);
}

如果我错了,并且用户将操纵这些值,您可以这样做(使用 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);
}
于 2012-07-16T13:36:21.393 回答