Search code examples
javascriptjqueryhtmlknockout.jsko.observablearray

Applying jQuery event functions to new Knockout.js array elements


I have a Knockout.js viewmodel with a list of products, which are populated by an ASP.NET Web API call:

// Define viewmodel
var myViewModel = {
    products = ko.observableArray([]);
};

// Apply knockout bindings
ko.applyBindings(vm);

// Function that obtains product data
function listProducts(viewmodel) {
    var productsQuery = "api/products/get";

    // Send an AJAX request
    $.getJSON(productsQuery).done(viewmodel.products);
}

When I call listProducts, each element is added successfully to the ff. HTML <ul>:

<ul data-bind="foreach: products">
    <li class="item">
        <data-bind="text: productName">
    </li>
</ul>

However, when each item is added, the jQuery function that applies to my .item elements:

$(".item").click(function () {
    $(this).toggleClass("selected");
});

does not get applied to these newly added elements.

Question: How do I add elements to the Knockout.js observableArray that will also inherit their corresponding jQuery methods?


Solution

  • Basically you need to go back to the knockout docs and read, read, read! Forget doing this with jquery, it's just not the ko way. Knockout frees you from this kind of coding style, you just need to grok it.

    hint:

    use the click binding and the css binding

    http://knockoutjs.com/documentation/css-binding.html

    As an aside you can also do this:

     $.getJSON(productsQuery).done(viewmodel.products);