Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
130
Row selection when using igGrid Knockout binding
posted

Does the Knockout binding for igGrid support a callback for changes in row selection?  I couldn't find it described in the help documentation.

Parents
No Data
Reply
  • 1015
    Suggested Answer
    posted

    I'm doing it, but it's messy right now until IG puts out a better way. (igGrid, IgniteUI 13.1.20131.2143)

    I put my igGrid initialization in a function like this:

    function loadControls(viewModel){/*init the grid in here so i have access to the view model*/}

    I then use the RowSelectors feature and handle the checkBoxStateChanged event like so:

    checkBoxStateChanged: function (evt, ui)
    {
    	//Knockout ViewModel, but it could just be an array
    	var boundModel = viewModel.selectedItems;
    	//the record in the grid					
    	var r;
    
    	if (ui.isHeader)
    	{
    		//clear my viewModel for later re-adds
    		boundModel.removeAll();
    
    		if (ui.grid.selectedRows().length > 0)
    		{
    			if (ui.state == 'on')
    			{
    				for (var i = 0; i < ui.grid.selectedRows().length; i++)
    				{
    					r = ui.grid.findRecordByKey(ui.grid.selectedRows()[i].id);
    					if (r != null)
    						boundModel.push(r);
    				}
    			}
    			return;
    		}
    	}
    
    	//my users could change the multiselect option on the fly
    	if (viewModel.allowMultipleSelections() === false)
    		boundModel.removeAll();
    
    	r = ui.grid.findRecordByKey(ui.rowKey);
    	if (r != null)
    	{
    		if (ui.state == 'on')
    			boundModel.push(r);
    		else
    			boundModel.remove(r);
    	}
    }

    To complete the "bindings" I also handle the rowsRendered event so it can select on paging, etc:

    rowsRendered: function (evt, ui)
    {
    	//Knockout ViewModel, but it could just be an array
    	var boundModel = viewModel.selectedItems;
    	var gridId = ui.owner.id();
    
    	//For each of my saved selected items
    	//select the checkbox on the grid
    	for (var i = 0; i < boundModel().length; i++)
    	{
    		//the item's primary key
    		var key = boundModel()[i].Id;
    		
    		for (var x = 0; x < ui.owner.rows().length; x++)
    		{
    			//the row contains the key on an attribute data-id="primarykey"			
    			var rowKey = ui.owner.rows()[x].getAttribute("data-id");
    			if (key == rowKey)
    			{
    				$('#' + gridId).igGridSelection('selectRow', x);
    			}
    		}
    	}
    }

    I know it's not clean, but it gets the job done.

Children