how to create multiple slickgrids with a single function - slickgrid

I have a problem which I cannot seem to solve. I need to create a function which loops over an array of datasets and creates an independent slickgrids for each dataset. The catch is that the functions need to be bound to each grid independently. For example:
// this part works fine
for(var i=0; i<domain.length; i++){
dataView = new Slick.Data.DataView();
grid = new Slick.Grid('#' + domain[i].name, dataView, domain[i].columns, domain[i].options);
var data = domain[i].data;
// this works well and I am able to create several slickgrid tables
... etc ...
The problem is that every grid is now called "grid". Therefore, when I bind a function like this:
// controls the higlighting of the active row
grid.highlightActiveRow = function () {
var currentCell;
currentCell = this.getActiveCell();
I get a result which affects all grids (or in some cases only one grid).
How do I create multiple, independent grids with associated functions??? The problems seems to be that I have created one object "grid" and then assign all functions using the syntax grid.xxx - but I dont know how to create a unique object on each itteration.
Any help would be most appreciated.
PS: slickgrid is just amazing!!
Thanks
//****** UPDATE *********
#Jokob, #user700284
Thank you both for your help. Here is where I have manged to get to:
var dataView;
function buildTable() {
for(i = 0; i<domains.length; i++){
dataView = new Slick.Data.DataView();
var d = domains[i];
grid = new Slick.Grid('#' + d.name, dataView, d.columns, grids.options);
var data = d.data;
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter); -- will be reinstated once i have this working
dataView.endUpdate();
arrOfGrids.push(grid);
};
};
Jakob - for now i am sticking to "for(i)" until I can wrap my head around your comment - which seems very sensible.
But, using the above, the grid data are not populating. I am not getting any js errors and the column headers are populating but not the data. The reference to d.data is definitely correct as I can see the data using the Chrome js debugger.
Any ideas? Many thanks for your help so far

Instead of assign all new grids to grid (in which case you overwrite the old one everytime you create a new one), push them to an array:
var arrayOfGrids = [];
for(var i=0; i<domain.length; i++) {
dataView = new Slick.Data.DataView();
arrayOfGrids.push(new Slick.Grid('#' + domain[i].name, dataView, domain[i].columns, domain[i].options));
// ....
Then, when you want to something with your grids, like adding the highlight-function, you loop over the array and do it for each element:
for ( var i=0; i<arrayOfGrids.length; i++ ) {
arrayOfGrids[i].highlightActiveRow = function () {
var currentCell;
currentCell = this.getActiveCell();
// ... etc...
BONUS
While we're at it, I would recommend that you use the forEach method that's available on the array-object when iterating over the arrays, rather than the for-loop. The unlike the loop, forEach creates a proper scope for your variables and it gets rid of the useless i-iteration variable:
var arrayOfGrids = [];
domain.forEach(function(d) {
dataView = new Slick.Data.DataView();
arrayOfGrids.push(new Slick.Grid('#' + d.name, dataView, d.columns, d.options));
// ....
And then the same for the other loop of course :)

You could try adding each of the grid instances to an array.You will be able to handle each of the grids differently if you want, by means of <arrray>[<array-index>]
var gridArr = [];
// this part works fine
for(var i=0; i<domain.length; i++){
dataView = new Slick.Data.DataView();
var grid = new Slick.Grid('#' + domain[i].name, dataView, domain[i].columns, domain[i].options);
var data = domain[i].data;
// this works well and I am able to create several slickgrid tables
... etc ...
gridArr.push(grid)
Then if you say gridArr[0] you can access the 1st grid,gridArr[1] second grid and so on.

Just in case anybody else is following this question - here is the working solution:
Many many thanks to #Jokob and #user700284
// default filter function
function filter(item) {
return true; // this is just a placeholder for now
}
var dataView;
function buildTables() {
for(i = 0; i<domains.length; i++){
dataView = new Slick.Data.DataView();
var d = domains[i];
grid = new Slick.Grid('#' + d.name, dataView, d.columns, options);
var data = d.data;
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
dataView.setFilter(filter);
dataView.endUpdate();
grid.invalidate();
grid.render();
arrOfGrids.push(grid);
};
};

Related

How to get Active (focused) slickgrid?

I have two slickgrid and one delete button,
When i click on delete,i want focused grid so that i will delete items.
How to get focused grid ?
This is what i have done so far....
function deleteRow(e, args){
//code to delete items from "grid"
var selectedrows = grid.getSelectedRows();
var len = selectedrows.length;
var itemNo = "";
for(var i=0;i<len;i++)
{
var data = grid.getData().getItem(selectedrows[i]);
dataView.deleteItem(data.id);
itemNo =data.id;
var url = "delete_Item_Master?itemNo="+itemNo;
$.get(url, {itemNo : itemNo},function(data) {
location.reload(true);
});
}
//code to delete items from "metalGrid"
var metalSelectedrows = metalGrid.getSelectedRows();
var mlen = metalSelectedrows.length;
var itemNo = "";
for(var i=0;i<mlen;i++)
{
var mData = metalGrid.getData().getItem(metalSelectedrows[i]);
meyalDataView.deleteItem(mData.id);
itemNo =mData.id;
var url = "delete_subItem?itemNo="+itemNo;
$.get(url, {itemNo : itemNo},function(data) {
location.reload(true);
});
}
}
But this code delete items from both grid..
I think that the correct way to do this is to write your own selection model. It should be a Singleton, and two grids should interact with it. It should know which grid was last active.
But you need to ask yourself is that behaviour is good. What if user will delete an item from another grid - because there's only one button. IMHO every grid should have it's own button. And I work for an ERP company where we got that dillemas everyday ;)

Retain expanded rows after databinding Kendo UI grid

This is my first time working with Kendo UI. I have a Kendo UI grid with child nodes. I want to retain the expanded rows after databinding. Right now its getting collapsed after a row is added in the child
I have tried suggestion from here
dataBound: function() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
But this expands the first row only.
How to retain rows? What am I missing?
Codepen
After a lot of playing around with your code example in CodePen, I believe I've come up with an elegant solution that works.
Having worked with Kendo UI for over three years, I've become pretty familiar with some of its inner workings. As such, I'm going to take advantage of one of these - the data-uid attribute. Kendo UI puts these on all <tr> elements in its grid. I chose this attribute because I know that when we call grid.expandRow() we're going to need to fashion a valid jQuery selector to pass in as a parameter. This eliminates the need for us to add our own attributes or classes and the code to handle them.
First, we need to define a variable to hold our row reference. We'll call it expandedRowUid. To set its value, we hook into the detailExpand event of the grid. So, when the user expands a row, we store its data-uid number.
var expandedRowUid;
var grid = $('#grid').kendoGird({
// ...
detailExpand: function(e) {
expandedRowUid = e.masterRow.data('uid');
}
});
Then, whenever a change is made that causes the master grid to re-bind to its data, we hook into the dataBound event of the grid and re-expand the row that has a data-uid equal to the one stored in expandedRowUid.
var grid = $('#grid').kendoGird({
// ...
detailExpand: function(e) {
expandedRowUid = e.masterRow.data('uid');
},
dataBound: function() {
this.expandRow($('tr[data-uid=' + expandedRowUid + ']'));
}
});
Here is the working CodePen example.
NOTE: This will only re-expand the last row that was expanded before the data bind is triggered. So, if you expand rows 4, 5, and 2 in that order, and then trigger a data bind, only row 2 will be re-expanded. You can obviously extend this functionality to handle use cases like that though.
GridDetailExpand: function (e) {
var gridId = e.sender.element[0].id;
var grid = $("#" + gridId).data("kendoGrid");
var data = grid.dataItem(e.masterRow);
addToArray(expandedRows, data.UniqueIdOfYourDataInGrid);
},
GridDetailCollapse: function (e) {
var gridId = e.sender.element[0].id;
var grid = $("#" + gridId).data("kendoGrid");
var data = grid.dataItem(e.masterRow);
removeFromArray(expandedRows, data.UniqueIdOfYourDataInGrid);
}
And then on databound
var gridId = e.sender.element[0].id;
var grid = $("#" + gridId).data("kendoGrid");
$.each(grid.tbody.find('tr.k-master-row'), function () {
var data = grid.dataItem(this);
if (isInArray(expandedRows, data.UniqueIdOfYourDataInGrid)) {
grid.expandRow(this);
}
});
Functions required:
var expandedRows = [];
function addToArray(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) return;
}
arr.push(value);
}
function removeFromArray(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
delete arr[i];
return;
}
}
}
function isInArray(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) return true;
}
return false;
}
Hope this helps ... took me a while to figure it out...
Solution for Retaining Last Expanding row in the parent grid after records added in the child grid get refreshed.
detailInit: function (e) {
//Get Parent Grid Last expanded Row index
lastRowIndex = $(e.masterRow).index(".k-master-row");
},
dataBound: function () {
//Check any parent grid row is expanded based on row index
if (lastRowIndex != null && lastRowIndex != undefined){
//find the Grid row details based on row index
var row = $(this.tbody).find("tr.k-master-row:eq(" + lastRowIndex + ")");
//If expand Row exists then it will expanded
this.expandRow(row);
}
else {
//None of the Parent Grid row is expanded then,default First row is expanded
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
}

Assigning functions to multiple slickgrids

Please help to solve this very annoying problem. I am using a for loop to iterate over an array of data and create multiple grids. It is working well but the filter function is not binding properly (it only binds to the LAST grid created) Here is the code:
// this function iterates over the data to build the grids
function buildTables() {
// "domain" contains the dataset array
for (i = 0; i < domains.length; i++) {
var dataView;
dataView = new Slick.Data.DataView();
var d = domains[i];
grid = new Slick.Grid('#' + d.name, dataView, d.columns, grids.options);
var data = d.data;
// create a column filter collection for each grid - this works fine
var columnFilters = columnFilters[d.name];
// this seems to be working just fine
// Chrome console confirms it is is processed when rendering the filters
grid.onHeaderRowCellRendered.subscribe(function (e, args) {
$(args.node).empty();
$("<input type='text'>")
.data("columnId", args.column.id)
.val(columnFilters[args.column.id])
.appendTo(args.node);
});
// respond to changes in filter inputs
$(grid.getHeaderRow()).delegate(":input", "change keyup", function (e) {
var columnID = $(this).data("columnId");
if (columnID != null) {
// this works fine - when the user enters text into the input - it
// adds the filter term to the filter obj appropriately
// I have tested this extensively and it works appropriately on
// all grids (ie each grid has a distinct columnFilters object
var gridID = $(this).parents('.grid').attr('id');
columnFilters[gridID][columnID] = $.trim($(this).val());
dataView.refresh();
}
});
//##### FAIL #####
// this is where things seem to go wrong
// The row item always provides data from the LAST grid populated!!
// For example, if I have three grids, and I enter a filter term for
// grids 1 or 2 or 3 the row item below always belongs to grid 3!!
function filter(row) {
var gridID = $(this).parents('.grid').attr('id');
for (var columnId in grids.columnFilters[gridID]) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var header = grid.getColumns()[grid.getColumnIndex(columnId)];
//console.log(header.name);
}
}
return true;
}
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
dataView.setFilter(filter); // does it matter than I only have one dataView instance?
dataView.endUpdate();
grid.invalidate();
grid.render();
In summary, each function seems to be binding appropriately to each grid except for the filter function. When I enter a filter term into ANY grid, it returns the rows from the last grid only.
I have spent several hours trying to find the fault but have to admit defeat. Any help would be most appreciated.
yes, it matters that you have only one instance of dataView. and also sooner or later you will come up to the fact that one variable for all grids is also a bad idea
so add a var dataView to your loop, it should solve the problem

AS3 URLRequest in for Loop problem

I read some data from a xml file, everything works great besides urls. I can't figure what's the problem with the "navigateURL" function or with the eventListener... on which square I click it opens the last url from the xml file
for(var i:Number = 0; i <= gamesInput.game.length() -1; i++)
{
var square:square_mc = new square_mc();
//xml values
var tGame_name:String = gamesInput.game.name.text()[i];//game name
var tGame_id:Number = gamesInput.children()[i].attributes()[2].toXMLString();//game id
var tGame_thumbnail:String = thumbPath + gamesInput.game.thumbnail.text()[i];//thumb path
var tGame_url:String = gamesInput.game.url.text()[i];//game url
addChild(square);
square.tgname_txt.text = tGame_name;
square.tgurl_txt.text = tGame_url;
//load & attach game thumb
var getThumb:URLRequest = new URLRequest(tGame_thumbnail);
var loadThumb:Loader = new Loader();
loadThumb.load(getThumb);
square.addChild(loadThumb);
//
square.y = squareY;
square.x = squareX;
squareX += square.width + 10;
square.buttonMode = true;
square.addEventListener(MouseEvent.CLICK, navigateURL);
}
function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
trace(tGame_url);
}
Many thanks!
In navigateURL() you use tGame_url, but I think you'd rather use something like tgurl_txt.text which will be different for each square.
Looks like you're not attaching the event listener properly. Instead of this.addEventListener, attach it to the variable you created when creating new square_mc..... so:
square.addEventListener(MouseEvent.CLICK, navigateURL);
you should add the addEventListener on the Squares
mmm..still figuring how eventhandler function will ever get the correct tgame_url var.
What if you try this:
square.addEventListener(MouseEvent.CLICK, function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
trace(tGame_url);
});
try tracing this:
function navigateURL(event:MouseEvent):void
{
var url:URLRequest = new URLRequest(tGame_url);
navigateToURL(url, "_blank");
//trace(tGame_url);
trace(event.currentTarget.tgurl_txt.text);
}
you should add the url to your square in the loop
square.theUrl = tGame_url;
in the event listener function you should be able to access it with
event.currentTarget.theUrl;

images and selectbox in jqgrid

hai i am very new to jquery and jqgrid..
i have implemented a grid...but i don't have any idea to display images in column from the corresponding database value...i tried a lot but failed ..can anybody help me..
regards
In the setup parameters add:
loadComplete: function() {
var ids = $("#list").getDataIDs();
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<img src='http://www.google.com/images/nav_logo6.png'>";
$("#list").setRowData(ids[i], { externalId: be })
}
},
In this example it will load the google logo. This sample goes over all the rows and adds the same item. You can change it do be more dynamic based on the current value of the cell etc.

Resources