Lambda like code with Javascript in KnockoutJS

KnockoutJS has a good set of utility functions built in under ko.utils which were actually part of ko, to make ko. However you might find them very useful in writing regular javascript code as well. I came across this example by rniemeyer on ko Google group, which works like lambdas in any language ( => in C#)

ko.utils.arrayFilter allows you to do a items.Where(i => i.type == myType) like statement.

var viewModel = {
    items: [
        { type: "a", name: "one" },
        { type: "b", name: "two" },
        { type: "a", name: "three" },
        { type: "b", name: "four" },
        { type: "b", name: "five" }
        ],
    filteredItems: function(type) {
        return ko.utils.arrayFilter(this.items, function(item) {
            return item.type == type;
        });
    }
};

The JSFiddle for the working sample is at http://jsfiddle.net/rniemeyer/Kbszh/

2 thoughts on “Lambda like code with Javascript in KnockoutJS”

    1. Thanks for the link, I did look at it, and it looks awesome, looks like it fits perfectly in to the bucket of “useful js libraries”. Right sized lego pieces to build rich client side apps. Planning to use it very soon.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>