淘汰赛JS - 绑定按钮将项目集合中 [英] KnockOut JS - Binding a button to an item in a collection

查看:154
本文介绍了淘汰赛JS - 绑定按钮将项目集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个稍微棘手的问题用语言来表达。基本上,我一直在努力的基础上,在该KnockoutJS网站(http://knockoutjs.com/examples/cartEditor.html)的例子之一KnockoutJS建立一个购物车页面。不过,我想利用jQueryUI的滑块,这样我可以在我的购物车调整各产品的值。

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.

这个我已经成功地获得工作确定,我可以添加一个产品(在这种情况下Motorcars),以我的购物篮和调整值也增大/减小因汽车是否具有运动套件或者是价值敞篷车。

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.

推荐答案

如果你打算使多个按钮,你可以创建一个可以创建你的事件处理程序可以采取在汽车类型的函数。

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>

更新小提琴

这篇关于淘汰赛JS - 绑定按钮将项目集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆