我正在使用这个插件http://www.joshbuckley.co.uk/2011/07/knockout-js-datatable-bindings/ 来处理数据表/ko 绑定。这是JS代码:
function ProductViewModel() {
// Init.
var self = this;
self.products = ko.observableArray();
self.singleProduct = ko.observable();
var mappedProducts;
// At first load i'm loading data.
$.getJSON("/admin/test", function(allData) {
mappedProducts = $.map(allData, function(item) {
var p = new Product(item);
// I'm adding a new property to my model, to handle row level actions.
// I'm not sure this is a good practice.
p.edit = "<button data-bind='click: $root.edit'><i class='icon-pencil'></i></button>";
return p;
});
self.products(mappedProducts);
});
// Here i'm using the basic switch pattern, as from KO tutorials.
self.edit = function(product) {
console.log(product); // <--- Prints the whole self.products() array
self.singleProduct(product);
self.products(null);
}
self.list = function() {
self.products(mappedProducts);
self.singleProduct(null);
}
}
// My model.
function Product(item) {
this.name = ko.observable(item.name);
this.dealer = ko.observable(item.dealer);
this.cost = ko.observable(item.cost);
this.price = ko.observable(item.price);
this.picture = ko.observable();
}
这是我的标记:
<table id="products-table" class="table table-striped table-bordered table-hover"
data-bind="dataTable: {data: $parent.products, options: {aoColumns: [
{ bSortable: false, mDataProp: null, sDefaultContent: '' },
{mData: 'name'},
{mData: 'dealer'},
{mData: 'cost'},
{mData: 'price'},
{ bSortable: false, mData: 'edit' }
]}}">
<thead>
<tr>
<th>Pic</th>
<th>Name</th>
<th>Dealer</th>
<th>Cost</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
我能够虚拟地在列表和编辑视图之间切换,绑定似乎得到了正确处理。
问题:在编辑处理程序中,我希望接收单个模型作为参数;我收到了整个系列,所以我无法识别要编辑的模型。
还有一件事:我完全不确定这是在行上绑定事件的好习惯,所以任何建议都将不胜感激!