Reputation: 177
I have this bound list:
<table id="product_list" data-bind="foreach : listProduct">
<tr>
<td data-bind="text:name"></td>
<td data-bind="text:description"></td>
<td><a data-bind="click:viewDetail">View detail</a></td>
</tr>
And here the modelview :
var load = {
listProducts : function(){
var self = this,
self.listProduct = ko.observableArray([]);
product.get().then(function(resp){
self.listProduct(resp);
self.viewDetail = function(data){
//some code here
};
});
}
}
Finally the binding:
ko.applyBindings(new load.listProducts(), document.getElementById("product_list"));
The first it's bind the first item of product and then show errorMessage:
Unable to process binding "click: function (){return click:viewDetail }"
So did I do something wrong? and how to fix it? Thank.
Upvotes: 0
Views: 58
Reputation: 1762
This is how I would recommend writing it. Hopefully you can find your answer by looking at my example.
<table id="product_list" data-bind="foreach: products">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: description"></td>
<td><a href="javascript:void(0);" data-bind="click: $parent.viewDetail">View detail</a></td>
</tr>
</table>
<script type="text/javascript">
$(function() {
var viewModel = {
products: ko.observableArray(),
viewDetail: function(product) {
console.log(product.name + ": " + product.description);
}
};
ko.applyBindings(viewModel, document.getElementById("product_list"));
$.getJSON("/some/url/products", function(data) {
// data = {"products": [{"name": "foo1", "description": "bar1"}, {"name": "foo2", "description": "bar2"}]}
$.each(data.products, function(key, val) {
viewModel.products.push(val);
});
});
});
</script>
Working example: https://jsfiddle.net/2nrrxnof/9/
Upvotes: 1