I am trying to implement the checkbox change event using angular but seeing the event firing multiple times when a checkbox is clicked.
I have created a plnkr for this, please help. Ideally it should be fired only once.
$scope.treeOptions = {
checkboxes: {
checkChildren: true
},
dataBound: function(e) {
$scope.attachChangeEvent(e);
}
};
Event change code:
$scope.attachChangeEvent = function(e) {
var dataSource = e.sender.dataSource;
// issue : change event is getting called multiple times for every click on checkbox
dataSource.bind("change", function(e) {
var selectedNodes = 0;
var checkedNodes = [];
$scope.checkedNodeIds(dataSource.view(), checkedNodes);
for (var i = 0; i < checkedNodes.length; i++) {
var nd = checkedNodes[i];
if (nd.checked) {
selectedNodes++;
}
}
// check the console - this is called multiple times for one checkbox click
console.log(selectedNodes);
});
};
Is there another event to attach to to have only one event fired after all checkboxes are updated? Or maybe there is a way to group all those 'change' events and fire just one instead?
The dataBound
event is triggered multiple times because you're dealing with a hierarchical data source (each child DS triggers the event, and it bubbles up). As a result, you're binding the change handler multiple times.
You should instead bind the change event from your initTree
method; snippet:
var knobj = new kendo.data.HierarchicalDataSource({
data: arrayObj
});
//setting heirarchial data to scope
$scope.treeObj = knobj;
$scope.attachChangeEvent();
Alternatively, you can use the dataBound
event and check e.node
, which is apparently undefined
for the last time dataBound is triggered (demo):
dataBound: function(e) {
if (!e.node) {
$scope.attachChangeEvent();
}
}