Home > javascript > Knockout JS Mapping fromJS nested models

Knockout JS Mapping fromJS nested models

January 27Hits:1

I am having trouble understanding how to work with Knockout JS Mapping Plugin. I have some nested models (as seen below) and what I am currently doing is just using the ko.mapping.fromJS() in the parent model. What I am noticing is that computed values are not being ...computed.

I tried to understand the "create":

var mapping = {     'children': {         create: function(options) {             return new myChildModel(options.data);         }     } } var viewModel = ko.mapping.fromJS(data, mapping); 

But right now in my current scenario I am not sure how to implemented.

Current structure:

var ProductModel = function($name, $price, $quantity) {     var self = this;      self.id = ko.observable();     self.name = ko.observable($name);     self.quantity = ko.observable($quantity);     self.price = ko.observable($price);     self.price.total = ko.computed(function() {         return self.price() * self.quantity();     }); };   var CartModel =  function (){    var self = this;     // Model Properties    self.id = ko.observable();       self.products = ko.observableArray();         self.fetch = function() {         $.ajax({             url: "route to get the specific cart",             type: "GET",             success: function(data) {                                 ko.mapping.fromJS(data, {}, self);             }         });     };         // Convert to mapping format     ko.mapping.fromJS(ko.mapping.toJS(self)); };  var ViewModel = ko.validatedObservable(new CartModel()); ko.applyBindings(new ViewModel()); 

I am not sure how to get the ProductModel to trigger the computed inside the ProductModel, I am not sure if I have to call the ko.mapping.fromJS inside every single Model (I have many more models, I stripped them out to make it simpler).

After the fetch function I alerted the products().length and it actually contains the quantity that was previously saved. but the computed is not showing. How do I implement the create method of knockout mapping plugin for nested observable(and observablearrays) that are models with computed inside of them.

P.S: The reason I have it self.price.total is in order to avoid the toJS send the total key as well. I can't ignore the properties of nested models using ignore:

See this thread for more: Knockout JS Mapping fromJS nested models


How does your ajax response looks like? Does it returns the whole cart, or just the products?

Anyway, if you want to handle your product list as an observableArray of viewmodels you could do something like this:

ko.utils.arrayForEach(products, function(item, index) {
  self.products.push(new ProductModel(item.name, item.price, item.qty);

If you want to use the mapping plugin, I haven't made a custom implementation of the "create" method, but I would do something like:

var ProductModel = function(product) {
  var self = this;

  ko.mapping.fromJS(product, {}, self);

  self.total = ko.computed(function() {
      return self.price() * self.quantity();


I have re-read your question, and I think this answer may be what you're looking for, the only downside of that approach, well for me at least, is that you would need to define a mapping config object for each viewmodel with nested viewmodels in your code

Related Articles

  • Knockout JS Mapping fromJS nested modelsJanuary 27

    I am having trouble understanding how to work with Knockout JS Mapping Plugin. I have some nested models (as seen below) and what I am currently doing is just using the ko.mapping.fromJS() in the parent model. What I am noticing is that computed valu

  • Map object data to view model function using ko.mapping.fromJSJanuary 26

    I have created a knockout js component as follows: define(['knockout', 'text!./details.html'], function(ko, htmlString) { function detailsViewModel(params) { var response = getDummyResponse(); // how to extend the view model with ko.mapping.fromJS()?

  • Unable to process binding, push JSON data to ObservableArray using ko.mapping.fromJSFebruary 15

    Can anybody explain what's wrong in my code, I am new to knockout... So, initially I receive json data from database and it works. Than when I click 'Add some' I want to add(push) same data from database to my observable array. The code below obvious

  • ComputedObservables doesn't recalc after ko.mapping.fromJSFebruary 8

    I'm using KnockoutJS and I have a nested ViewModel-Structure with Computed Observables on each level. The parent levels contains totalization of it's children. The datastructure looks like this (simplyfied): vm.clientsRawData = [ { ClientName: "Thoma

  • Rails - Why does my nested model form not require 'accepts_nested_attributes_for'February 9

    I have two models item and user_item. Item has many user_items and user_items belongs to item. I have a form where a user can create a new item. In the form a user should include a picture. The name, description, and tags get saved to a new item obje

  • Trying to update nested model first on before_saveFebruary 11

    I am calculating :price in my nested item model in order to map it in my invoice model. The problem is that the before_save in the invoice model is being called first and I want it to be called after the before_save in the nesteditem model Any ideas

  • Before validation on nested modelJanuary 9

    I have a nested model items and I am trying to multiply two columns together cost and quantity to set the last column price. I need to set the column price before the form is saved and i need to also validate the model. The before_validation call bac

  • Nested Iteration with model builder - using nested models

    Nested Iteration with model builder - using nested modelsSeptember 7

    I'm new to using model builder and have to do a nested iteration (for every month I have to iterate through 6 parameters). I am thinking of doing that by using nested models. One model doing the interation through monthes and then providing the curre

  • PHP MVC class with controller and nested model

    PHP MVC class with controller and nested modelNovember 26

    I had asked a first question about this class a while ago and got a few answers here which made me rewrite it completely. I removed all statics and globals, added my variables as arguments for the constructor, and pass them again as reference through

  • Problem validating parent model with nested models in modelbuilder

    Problem validating parent model with nested models in modelbuilderMarch 24

    I have a parent model with several nested models. I'm having trouble getting the parent model to validate. The issue is with sub model 4. The two screenshots are of the parent model and sub model 4. The output from sub model 3 feeds into parameter "M

  • Using global parameters in nested models of ModelBuilder?October 22

    I have a model that consists of two nested models and various parameters. There are two parameters that are common to all of the models (including the overall "grand" model). The common parameters are in-line variables and serve to assign unique

  • Rails routes for self nested modelsJanuary 15

    In my rails app I have a Task model. In my app, my tasks can have substasks and so on. Since my subtasks are tasks with only a parent task, I did a self-nested model such as class Task < ActiveRecord::Base ## Self Join has_many :subtasks, class_name:

  • Creating Instance of Nested model inside parent controllerJanuary 18

    I would like to know if it is possible to create an instance of a nested model inside the parents controller. Let me explain. I have a model called Museum and another model called Museumimage. Museumimage has only one field which is an attachment, ma

  • Rails nested models and virtual attribute initializationJanuary 27

    I have a problem understanding how are attributes "sent" to nested model(s), and if is possible to do this for model with virtual attrubute too. I have three models: class User < ActiveRecord::Base ... has_and_belongs_to_many :clearancegoods

  • Adding new Observable to ObservableArray mapped by ko.mapping.fromJSFebruary 10

    I'm trying to add a new Observable to an ObservableArray which has been mapped initially with KO's mapping plugin. But I don't get that working. Firebug is telling me "TypeError: totalChf is not a function". Looking at the added Observable, I no

  • rails with most nested models and cocoon gem;

    rails with most nested models and cocoon gem;February 16

    I have a rails4 app with nested model form. There is a product model that has_many product_features, has_many product_usecases and has_many product_competitors. Everything works fine except when I load the page only the first nested model (product_fe

  • Height Map vs 3D Model MeshApril 28

    I'm currently working on a 3D PC game (written in C++ and DirectX 9.0) and I'm trying to find the best way to store level data in the memory. The game's action takes place under the ground, so there's always a ceiling above the player. The ground is

  • Map a fbx model between 2 VertexPositionColor Positions

    Map a fbx model between 2 VertexPositionColor PositionsMay 27

    I have created a VertexPositionColor position and drew it in the XNA like this VertexPositionColor[] backbone; backbone = new VertexPositionColor[2]; backbone[0].Position = new Vector3(0, 22, 0); backbone[0].Color = Color.Black; backbone[1].Position

  • What uses are there for multiple UV maps on a model?July 24

    I'm trying to think of some reasons why there might be more than one UV map on a mesh. Usually I just unwrap the model, and the same UV map works for both the diffuse color texture, the bump map texture, and any other textures I chose to add. Are the

  • Model builder - Nesting models to extract raster values to points

    Model builder - Nesting models to extract raster values to pointsFebruary 23

    Hello! Hopefully a quick question. I have a simple model below that iterates through a folder full of rasters, taking each in turn to extract data values based on a single shapefile of Random point locations. The rest works over the points table to a

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 1.896 s.