简体   繁体   中英

ko.observableArray and JSON data massaging

I'm using web services to load data to client side. For binding purposes I need to expand on data that I get. Ie I don't want to massage all data on server side.

For example, object Trip { Id: "123", Status: "P" }

In HTML I bind table to observableArray and want to display "Pending" instead of "P". I'm coming from Silverlight/MVVM and usually you would use converter or just add new R/O property to object.

Not sure how this scenario should be handled in knockout.js

You may find here all you need :

http://net.tutsplus.com/sessions/knockout-succinctly/

Have a good read.

If you are just looking for a converter, computed observables are a good candidate.

var Tip = function(data) {
    var self = this;
    self.id = data.id;
    self.status = ko.observable(data.status);

    //You may prefer fullStatus, or statusName
    self.statusConverter = ko.computed(function() { 
        return self.statusMap[self.status()];
    });
};

Tip.prototype.statusMap = {
    P: "Pending",
    O: "Open",
    C: "Closed"
};

which you can bind to like this:

<td data-bind="text: statusConverter"></td>

You can see it in this fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM