PercivalMcGullicuddy
PercivalMcGullicuddy

Reputation: 5533

Using knockout to copy objects from one array to another

I'm using a Webforms page. On it I have a KnockoutJS ViewModel that gets a serialized JSON list of "Customers" by making a call to the backend C# code.

I data-bind that array to a combobox and I want to add the selected Customer to another array when a button is clicked. I want the list of selected customers to appear in a simple unordered list.

I'm not quite sure how add Customers to the "SelectedCustomers" property when clicking on the "Add" button. Note: I don't wan't move them, just copy.

Javascript/Knockout Bindings

<script type="text/javascript">
    $(document).ready(function() {

        function CustomerViewModel() {
            var self = this;

            self.Customers= <%= getJson() %>;
            self.SelectedCustomers = ko.observableArray([]);

            //operations
            self.addCustomerToList = function() {
                //Add selected customer to self.SelectedCustomers 
            }

        }

        ko.applyBindings(new CustomerViewModel());
    });
    </script>

HTML elements

<select data-bind="options: Customers, optionsText: 'CustomerName', value: CustomerID, optionsCaption: 'Select a Customer to Add'"></select>

<button type="submit">Add Customer</button>

Selected Customers:

<ul data-bind="foreach: SelectedCustomers">
 <li><span data-bind="text: CustomerName"></span></li>
</ul>

Upvotes: 0

Views: 1994

Answers (3)

PercivalMcGullicuddy
PercivalMcGullicuddy

Reputation: 5533

I was able to figure this out. Check out my solution here:

http://jsfiddle.net/6vBsm/1/

function ViewModel() {
    var self = this;

    self.Components = ko.observableArray([{
        "ID": "1",
            "Name": "Tennis Ball",
            "Description": "Basic Yellow Tennis Ball 9",
            "Quantity": 0,
            "Price": 1.99,
            "Discount": 0.0,
            "FreePeriods": 0
    }, {
        "ID": "2",
            "Name": "Hockey Stick",
            "Description": " Premium Carbon Fiber Construction",
            "Quantity": 0,
            "Price": 67.99,
            "Discount": 0.0,
            "FreePeriods": 0
    }, {
        "ID": "3",
            "Name": "Cycling Helmet",
            "Description": " For going fast.",
            "Quantity": 0,
            "Price": 226.99,
            "Discount": 0.0,
            "FreePeriods": 0
    }]);

    self.componentToAdd = ko.observable();
    self.SelectedComponents = ko.observableArray([]);


    // Computed data
    self.totalSurcharge = ko.computed(function () {
        var total = 0;
        for (var i = 0; i < self.SelectedComponents().length; i++)
        total += self.SelectedComponents()[i].Price;
        return total;
    });


    //Operations
    self.addComponent = function () {
        var mycopy = JSON.parse(ko.toJSON(self.componentToAdd()));
        self.SelectedComponents.push(mycopy);
    };

}

ko.applyBindings(new ViewModel());

Upvotes: 0

nickvane
nickvane

Reputation: 2999

You can databind the selected customer from the list to another array (ChosenCustomers). See http://knockoutjs.com/documentation/selectedOptions-binding.html

<select data-bind="selectedOptions: ChosenCustomers, options: Customers, optionsText: 'CustomerName', value: CustomerID, optionsCaption: 'Select a Customer to Add'"></select>

In the javascript class the ChosenCustomers array is defined:

self.Customers= <%= getJson() %>;
self.SelectedCustomers = ko.observableArray([]);
self.ChosenCustomers = ko.observableArray([]);

In the method we check if it's not already there and if not add it to the SelectedCustomers array.

self.addCustomerToList = function() {
    self.ChosenCustomers.each(function(index, item){
        if(self.SelectedCustomers.indexOf(item) < 0){
            self.SelectedCustomers.push(item);
        }
    });
};

Note: although your combobox may only allow for 1 customer to be selected at a time, the selectedOptions binding will always be an array, but will only have 1 item in it.

Upvotes: 2

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

Lets say you want to copy self.SelectedCustomers = ko.observableArray([]);

Then use slice function of knockout like below

self.newselectedCustomers(self.SelectedCustomers().slice(0));

Upvotes: -1

Related Questions