Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout mapping with computed fields

I'm getting data from a WCF service,and i map, and bind the data with my DOM object :

var PayinyVM = {};

    $.getJSON('/service/PaidService.svc/PaidList', function (data) {
        var tmp = JSON.stringify(data.d);

        PayinyVM.model = ko.mapping.fromJSON(tmp);
        ko.applyBindings(PayinyVM);
    }); 

the result is shown as excepted on my DOM bind it to model. What I couldn't find out is how to add some computed observable let's say my data is returning people with FirstName and LastName, how can I make a computed observable FullName with FN + ' ' + LN.

like image 641
Frenchi In LA Avatar asked Jun 05 '12 23:06

Frenchi In LA


People also ask

Which function is used for computation in knockout?

In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.

What is Ko computed in knockout JS?

ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.

How do you get the knockout value from observable?

To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .


1 Answers

Here's a working copy of your fiddle, I had to make a lot of assumptions as your fiddle wasn't even correct javascript and seemed quite confused and didn't even reference knockout

var PaidPeople = function(data) {
    var self = this;
    ko.mapping.fromJS(data, {}, this);
    this.fullName = ko.computed(function () {
                    return self.Name() + " : just ";
                });
}

var PayinyVM = function (data) {
                var self = this;

                ko.mapping.fromJS(data, {
                    'model' : {
                        create: function(options) {
                            return new PaidPeople(options.data);
                    }                        
                  }
                }, self);                
            };

var data = {model:[{__type: "PaidPeople:#model", Amount:110, Attendee:1, Name:'John'}]};

ko.applyBindings(new PayinyVM(data)); ​

and a fiddle that works : http://jsfiddle.net/qeUHd/

like image 195
Keith Nicholas Avatar answered Sep 26 '22 22:09

Keith Nicholas