FloatLeft
FloatLeft

Reputation: 1337

KnockOut JS - Binding a button to an item in a collection

This is a slightly tricky question to put into words. Basically I've been trying to build a shopping cart page in KnockoutJS based on one of the examples in the the KnockoutJS website (http://knockoutjs.com/examples/cartEditor.html). However I wanted to make use of jQueryUI sliders so that I could adjust the values of each product in my cart.

This I've managed to get working OK and I can add a product (in this case Motorcars) to my basket and adjust the value and also increase/decrease the value depending on whether the car has a sports kit or is a convertible.

http://jsfiddle.net/FloatLeft/UjRrJ/

However, instead of adding a product (the "Add Car" button) and then choosing the car type, I want to be able to add a specific type (eg BMW, Ford) to the cart at the click of the button (eg clicking on the "Add BMW" button - this does nothing at the moment).

However my simple brain cant work out how to bind the button to a specific car in the collection. I think I can retrieve the car by creating a function that iterates over the collection and finds the car that has the type that matches a string, e.g.

    function GetCar(carType) {
        for (var i = 0; i < sampleCars.length; i++) {
            if (sampleCars[i].Type == carType) {
                return sampleCars[i];
            }
        }
    }

So basically I want to know how I can bind the click event of "Add BMW" button to a particular car in the collection and have that added to my cart.

Upvotes: 0

Views: 215

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134571

If you plan on making multiple buttons, you can create a function which can create your event handlers which can take in a car type.

self.addSpecificCarLine = function (carType) {
    return function () {
        var car = ko.utils.arrayFirst(sampleCars, function (car) {
            return car.Type === carType;
        });
        var cartLine = new CartLine();
        cartLine.car(car);
        self.lines.push(cartLine);
    };
};

Then you can bind to the handlers like so:

<button data-bind='click: addSpecificCarLine("BMW")'>Add BMW</button>

Updated fiddle

Upvotes: 3

Related Questions