Okky
Okky

Reputation: 10466

How to get back knockout observable binded by knockout-mapping

I have binded my json array to knockout by using knockout-mapping plugin

JSON

{
   "info":[
      {
         "Name":"Noob Here",
         "Major":"Language",
         "Sex":"Male",
         "English":"15",
         "Japanese":"5",
         "Calculus":"0",
         "Geometry":"20"
      },
      {
         "Name":"Noob Here",
         "Major":"Calculus",
         "Sex":"Female",
         "English":"0.5",
         "Japanese":"40",
         "Calculus":"20",
         "Geometry":"05"
      }
   ]
}

Binded using knockout-mapping plugin

var data = [];
$.each(data1.info, function (index, element) {
            data.push({
                English: element.English,
                Japanese: element.Japanese,
                Calculus: element.Calculus,
                Geometry: element.Geometry,
                name: element.Name,
                major: element.Major,
                sex: element.Sex
            });
        });

        dataFunction.prototype = function () {
            var getAllItems = function () {
                var self = this;
                ko.mapping.fromJS(data, {}, self.Items);
            };

Now I want to alert the value of English.

I tried alert(this.English()); inside dataFunction.prototype and it doesn't work.

How to alert that value?

JS-Bin code: http://jsbin.com/ipeseq/4/edit

Upvotes: 2

Views: 312

Answers (1)

Rune Vejen Petersen
Rune Vejen Petersen

Reputation: 3239

You need to define a proper view model and work from that in your mark-up.

I put together a view model with a custom view model mapping where I map your data into objects I called 'Student' that you can use in your markup. This object I extended with a ko.computed that calculates the total (It is in this object you can read and manipulate your observables).

 var Student = function(data) {
 var self = this;
 ko.mapping.fromJS(data, { }, self);
 self.total = ko.computed(function() { // Calculate total here
   return self.English() + self.Japanese() + self.Calculus() + self.Geometry();
    });
 };

var viewModelMapping = {  // Map all objects in 'info' to Student objects
'info': {
 create: function(options) {
        return new Student(options.data);
        }
    }
};

var ViewModel = function(data) {  // Create a view model using the mapping
    var self = this;
    ko.mapping.fromJS(data,viewModelMapping,self);
}

$(document).ready(function () {
    vm = new ViewModel(data);
    ko.applyBindings(vm);
});      

You can see the resulting JSBin code here

You can read more in the Customizing object construction using “create” and Customizing object updating using “update” sections here

Upvotes: 1

Related Questions