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

巧了我就是萌 提交于 2019-12-25 02:58:43

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/12751387/knockout-js-binding-a-button-to-an-item-in-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!