javascript - Knockout observableArray item property change doesn't update UI -
when change property observablearray
not update ui
see example below , in jsfiddle.
clicking on header should update sorting
property , show/hide appropriate span
javascript:
var basemodel = [{ key: 'name', type: 'string' }, { key: 'surname', type: 'string' }, { key: 'age', type: 'integer' }] var data = [{ name: "john", surname: "smith", age: 12 }, { name: "peter", surname: "klark", age: 3 }, { name: "steve", surname: "heisenberg", age: 43 }] var vm = function () { var counter = 1; var people = ko.observablearray(data); var keys = ko.observablearray([]); var init = function () { var temparray = []; _.each(basemodel, function (item, key) { temparray.push({ key: item.key, type: item.type, sorting: false, direction: "asc" }); }); // set first column sort default temparray[0].sorting = true; // add keys(temparray); }; var peoplelist = ko.computed(function () { return people.sort(function (l, r) { var sortkey = _.where(keys(), { sorting: true }) || keys()[0]; var result; if (typeof sortkey !== "undefined" && sortkey.length > 0) { result = (sortkey[0].direction === 'asc') ? l[sortkey[0].key] > r[sortkey[0].key] ? 1 : -1 : l[sortkey[0].key] < r[sortkey[0].key] ? 1 : -1; } else { result = l[0] > r[0] ? 1 : -1; } return result; }); }); var addkey = function () { keys.push({ key: "new key no " + (counter++), type: 'string', sorting: false, direction: 'asc' }); } var sortcolumn = function (v) { if(v.sorting === true){ v.direction = (v.direction === 'asc') ? 'desc' : 'asc'; } else { _.each(keys(),function(item,key){ keys()[key].sorting = false; }) keys()[keys().indexof(v)].sorting = true; } keys.valuehasmutated(); } init(); return { people: people, keys: keys, addkey: addkey, peoplelist: peoplelist, sort: sortcolumn } } ko.applybindings(new vm());
html:
<table> <thead> <tr data-bind="foreach: keys"> <td data-bind="click: $root.sort"> <span data-bind="text: $data.key"></span> <span data-bind="visible: $data.sorting, text: 'sorting'"></span> </td> </tr> </thead> <tbody data-bind="foreach: peoplelist"> <tr data-bind="foreach: $root.keys"> <td data-bind="text: $parent[$data.key] || 'no data'">1</td> </tr> </tbody> </table> <button data-bind="click: addkey">add new key</button>
you can make sorting property observable:
temparray.push({ key: item.key, type: item.type, sorting: ko.observable(false), direction: "asc" });
i've modified based on fiddle: http://jsfiddle.net/4ldzh/
Comments
Post a Comment