我想使用datatable knockoutjs綁定將數據呈現到表中。 我正在使用下面的鏈接和代碼將數據呈現到表中。 http://datatables.net/dev/knockout/使用knockoutjs的數據表綁定數據綁定
我在上面的例子中做的唯一變化是在渲染年齡數據時,我添加了輸入框在年齡列中記錄和在表格底部更新按鈕,以便用戶可以更改他的年齡並單擊更新按鈕數據應該自動更新,並在下一頁它應該反映在表中。
我面臨的問題是我無法更新本地js「人員」模型,因此無法使用knockoutjs綁定更新的數據。
ko.observableArray.fn.subscribeArrayChanged = function(addCallback, deleteCallback) {
var previousValue = undefined;
this.subscribe(function(_previousValue) {
previousValue = _previousValue.slice(0);
}, undefined, 'beforeChange');
this.subscribe(function(latestValue) {
var editScript = ko.utils.compareArrays(previousValue, latestValue);
for (var i = 0, j = editScript.length; i < j; i++) {
switch (editScript[i].status) {
case "retained":
break;
case "deleted":
if (deleteCallback)
deleteCallback(editScript[i].value);
break;
case "added":
if (addCallback)
addCallback(editScript[i].value);
break;
}
}
previousValue = undefined;
});
};`
`var data = [
{ id: 0, first: "Allan", last: "Jardine", age: 86 },
{ id: 1, first: "Bob", last: "Smith", age: 54 },
{ id: 2, first: "Jimmy", last: "Jones", age: 32 }
]; `
`var Person = function(data, dt) {
this.id = data.id;
this.first = ko.observable(data.first);
this.last = ko.observable(data.last);
this.age = ko.observable(data.age);
// Subscribe a listener to the observable properties for the table
// and invalidate the DataTables row when they change so it will redraw
var that = this;
$.each([ 'first', 'last', 'age' ], function (i, prop) {
that[ prop ].subscribe(function (val) {
// Find the row in the DataTable and invalidate it, which will
// cause DataTables to re-read the data
var rowIdx = dt.column(0).data().indexOf(that.id);
dt.row(rowIdx).invalidate();
});
});
};
$(document).ready(function() {
var people = ko.mapping.fromJS([]);
//loadData();
var dt = $('#example').DataTable({
"bPaginate": false,
"bInfo" : false,
"bAutoWidth" : false,
"sDom" : 't',
"columns": [
{ "data": 'id' },
{ "data": 'first' },
{ "data": 'age',
"mRender": function (data, type, row) {
var html = '<div style="display:inline-flex">' +
'<input type="text" class="headerStyle h5Style" id="ageId" value="'+data()+'"/>' +
'</div>';
return html;
}
}
]
});
// Update the table when the `people` array has items added or removed
people.subscribeArrayChanged(
function (addedItem) {
dt.row.add(addedItem).draw();
},
function (deletedItem) {
var rowIdx = dt.column(0).data().indexOf(deletedItem.id);
dt.row(rowIdx).remove().draw();
}
);
// Convert the data set into observable objects, and will also add the
// initial data to the table
ko.mapping.fromJS(
data,
{
key: function(data) {
var d = data;
return ko.utils.unwrapObservable(d.id);
},
create: function(options) {
return new Person(options.data, dt);
}
},
people
);
});
HTML代碼:<表CELLPADDING =「0 「cellspacing =」0「border =」0「class =」display cell-border「id =」example「> \t \t \t \t \t \t ID \t \t \t 名稱 \t \t \t 年齡 \t \t \t \t
\t 個 \t \t \t \t \t \t \t \t \t \t – Guddyaaa謝謝! Carpetsmoker爲您的努力:-) – Guddyaaa