I have an ASP.NET Web API method that returns a list of products:
public async Task<IEnumerable<Product>> Get()
{
var products = new IEnumerable<Product>();
// Data populated here
return products;
}
This API call is used by a Knockout.js observableArray:
// 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);
}
I would like to apply a click binding to these products, which would be a method named myClickFunction in this case. If possible, the method should be a function belonging to the objects that are returned by my Web API call :
<ul data-bind="foreach: products">
<li class="item" data-bind="text: productName, click: myClickFunction">
</li>
</ul>
Is it possible for me to add a function to the Web API result, which I can then use in the observableArray?
myClickFunctioncomes from the server (returned by Web API call), or that you want to decorate each object with this function in your client code? If this is the former (which is not a good idea, actually), see this question, it it's the latter - just use arraymapfunction in yourdone()callback and add this callback to each of returned products.