0

I have a list of items and each item consists of a number of text fields. The text fields need to be observables with an event handler on them such that if the user changes an entry, the event handler is called and actioned accordingly.

Here's the array declaration:

self.items = ko.observableArray(ko.utils.arrayMap(items, function(item) {
    return { quantity: item.quantity, size: item.size };
}));

...and there's a textbox for the total quantity. Basically, on editing the quantity in the rows of the array, I need the textbox to display the running total:

Total: input data-bind='value: total'

I've created a JSFiddle here:

http://jsfiddle.net/phykell/HyYFq/

The idea is that if the user enters/changes a quantity in one of the items, the sum-totals are updated for the given size and the resulting TOTAL value will be updated.

Any advice welcome - should I be trying to use the method described here:

http://knockoutjs.com/documentation/unobtrusive-event-handling.html

Thanks for looking :)

1 Answer 1

1

You should use ko.computed function. The quantity and size need to be observable to update the Total. So need to think as Object Oriented and need to be a model as the Item.

var initialData = [
    { quantity: "100", size: "8" },
    { quantity: "200", size: "10" }
];
var Item = function (q, s) {
    this.quantity = ko.observable(q),
    this.size = ko.observable(s)
}
var ItemsModel = function(items) {
    var self = this;
    self.items = ko.observableArray(ko.utils.arrayMap(items, function(item) {
        return new Item(item.quantity, item.size);
    }));
    self.addItem = function() {
        self.items.push(new Item(1,1));
    };
    self.removeItem = function(item) {
        self.items.remove(item);
    };
    self.total = ko.computed(function() {
        var total = 0;
        ko.utils.arrayForEach(this.items(), function(item) {
            total += item.quantity() * item.size();
        });
        return total;
    }, self);
};

ko.applyBindings(new ItemsModel(initialData));

Live: http://jsfiddle.net/HyYFq/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast reply and the JSFiddle explaining it - much appreciated! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.