I am using kendo grid's onDataBound
event to do something. Here's my jQuery code:
console.time('withoutnot');
jQuery(e.sender.dataSource._data).each(function (i, v) {
if (v.IsReadonly) {
e.sender.wrapper.find("tr[data-uid='" + v.uid + "'] .k-button")
.each(function (i, j) {
if (!jQuery(this).hasClass('k-grid-edit') && !jQuery(this).hasClass('k-grid-Desc')) {
jQuery(this).addClass('k-state-disabled').prop('disabled', true)
.prop('title', 'Readonly.');
}
});
}
});
console.timeEnd('withoutnot');
onDataBound
event gets raised once the grid has completed data-load from serverside.
My problem is that, because of 400 rows in the grid (without paging), it takes around 355ms
to 378ms
, which is still slower for me, because it causes visible performance lag in the grids load(readonly button effect).
How can I improve this code snippet even more? or is it the best I can go for?
NOTE: using native for
or jQuerys :not
(instead of those if conditions), proved disaster to me, load time scaled to 460ms
to 550ms
.
I am using jQuery 1.7.1
1 Answer 1
I found out solution to my problem. so basically this is what I learnt
- use filter to reduce the set of similar items instead of explicit if condition
- use cached variables i.e.
var $this = $(this);
- use methods chaining
and if same methods are to be used multiple times, try using it like:
.prop({ disabled: true, title: 'Readonly.' });
instead of call
.prop
(or any other) multiple times.try to scope restrict the context of your selector as far as you can, i.e.
jQuery("tr[data-uid='" + v.uid + "'] .k-button", e.sender.wrapper)
so here's my final query:
jQuery(e.sender.dataSource._data).each(function (i, v) {
if (v.IsReadonly) {
jQuery("tr[data-uid='" + v.uid + "'] .k-button", e.sender.wrapper)
.filter(function (i) {
var $this = jQuery(this);
return !($this.hasClass('k-grid-edit') || $this.hasClass('k-grid-Desc'));
})
.addClass('k-state-disabled')
.prop({ disabled: true, title: 'Readonly.' });
}
});
and this query took 267ms
- 296ms
(for 10 iterations)
-- I hope there can still be something even more faster like getting rid of that parent .each
loop
:not
as I'd expect it to be even with your filter and more elegant \$\endgroup\$e.sender.wrapper.find("tr[data-uid='" + v.uid + "'] .k-button:not(.k-grid-edit,.k-grid-Desc )")
. This would save me the need of that inner if condition.But Pseudo selectors are superbly slow \$\endgroup\$