Brad Bamford
Brad Bamford

Reputation: 3873

How to add a new anonymous items using knockout mapping plugin

I can't seem to get the Knockout Mapping Plugin to execute the "create" method (of Items) when I attempt to add a new Item into my array. It seems to execute on the initial creation from json, but not on adding new Items.

Here's a very simplified jsFiddle

Note: I've looked at similar questions but they all reference static objects that I don't have.

Inital JSON

var json = {    
  "Items": [{
        "ItemID": 1,
        "ItemDate": "2000-01-02T00:00:00Z",
        "Amount": 50
    },{
        "ItemID": 2,
        "ItemDate": "2000-01-02T00:00:00Z",
        "Amount": 100
    }]
};

Mapping Options

 var mappingOptions = {    
  "Items": {
    create: function (mappingoptions) {
        var data = mappingoptions.data;

        data = data || {
            "ItemID": ko.observable(0),                        
            "ItemDate": ko.observable(currentDate),                        
            "Amount": ko.observable(new Date())
        };

        var result = ko.mapping.fromJS(data);                                     
        return result;            
    }
  }
};

View Model (With Add Method)

MyApp.Batch.ViewModel = function (jsonBatch) {
  //Works Great
  var model = ko.mapping.fromJS(jsonBatch, mappingOptions); 

  //Doesn't Work
  model.addItem = function() {        
    // TRYING TO ADD a new Empty Item USING THE AUTO MAPPER        
    var newItem; 
    model.Items.push(ko.mapping.fromJS(newItem, mappingOptions))        
  };    

  return model;
};

Upvotes: 2

Views: 373

Answers (1)

nemesv
nemesv

Reputation: 139798

The mapping plugin's goal (as the name implies) is to map between object graph and not creating new objects for stretch. So it does not offer any features which could help you in this use case...

However your Items create function already deals with empty item case so you can directly call this function in your addItem method:

model.addItem = function() {
    model.Items.push(mappingOptions.Items.create({}));
};  

Demo JSFIddle.

Upvotes: 2

Related Questions