Howto check if line exists in an observable Array?

4,517 views
Skip to first unread message

Patrick

unread,
Apr 30, 2011, 5:20:03 AM4/30/11
to KnockoutJS
Hello,

I am working on an implementation that is related to the shopping cart
example (http://knockoutjs.com/examples/cartEditor.html).

The change here is, that I want one button for each product. If that
button is clicked a cartline is created with quantity 1.

What do I have to do to change this behaviour so, that on the second
click of the button the quantity is increased instead of a new line
that is added? My strategy would be to check, if the value of the
button is already existing, but I don't see how/where to do this.

There is no need to edit the lines of the table inline - items should
be added on click on the button (it's for a touchpad shopping cart
with a button per shopping item)

My code this far:

the button in the form

<div id="item1000" class="item category22"
data-bind="click: addLine({id: 1000, title: 'productname,
price: '1900'})">
<span class="title">productname</span>
<span class="price">1900</span>
</div>

the javascript

var cartLine = function(options) {

this.id = ko.observable(options.id);
this.product = ko.observable(options.title);
this.price = ko.observable(options.price);
this.quantity = ko.observable(1);

this.increaseQuantity = function(){
this.quantity(this.quantity() + 1);
};

this.subtotal = ko.dependentObservable(function(){
return this.product() ? this.product().price * parseInt('0' +
this.quantity(), 10) : 0;
}.bind(this));

};
var cart = function() {

this.lines = ko.observableArray([]);
this.addLine = function(options){
this.lines.push(new cartLine(options));
};

};

thanks for help
Patrick

rpn

unread,
Apr 30, 2011, 5:30:20 PM4/30/11
to knock...@googlegroups.com
Hello-
You should be able to modify your addLine function to be something like:

    this.addLine function(options{
        //see if we already have a line for this product
        var matchingLine ko.utils.arrayFirst(this.lines()function(line{
           return line.product(=== options.title
        });
        
        if (matchingLine{
             matchingLine.increaseQuantity()
        else {
           this.lines.push(new cartLine(options))
        }
    };


Here is a sample based on your code: http://jsfiddle.net/rniemeyer/GsByq/

A couple other small things:
-In the data-bind for your button, if you are going to pass parameters, then you have to call it as an anonymous function. 
-In your sub-total dependentObservable you try to access this.product().price instead of just this.price().

Hope this helps.





Patrick

unread,
Apr 30, 2011, 11:13:14 PM4/30/11
to KnockoutJS
Thank you, that did exactly what I needed. I think I need a closer
look into ko.utils.

Regards,
Patrick
Reply all
Reply to author
Forward
0 new messages