extjs treenode appendchild not working correctly - extjs

I have a treepanel which is loaded on demand from a web rest api. The rest api will return an array with the data according to the id of the selected node. Here is the code:
itemdblclick: function(item, record, eOpts) {
var store = Ext.getStore('mystore');
var newStore = Ext.create('mystore', {
autoDestroy: true,
storeId: 'otherId'
});
var parentid = record.data.id;
var that = this;
newStore.proxy.extraParams = {...};
newStore.autoDestroy = true;
newStore.storeId = 'otherId';
newStore.load({
callback: function(items) {
var node = store.getRootNode().findChild('id', record.data.idelement, true);
for (var i = 0, l = items.length; i < l; i++) {
var item = items[i].data;
var child = {..., idparent: parentid};
var newnode = node.createNode(child);
node.appendChild(newnode, true);
}
node.expand();
}
});
}
Thanks to norbeq who gave me the light to change the id of the second store. The thing is the tree is nicely populated and the node is expanded, but (why there is always a but?) next the expanded node there is no a -, the + remains the same.
This is what I mean:
I've sourrounded in red that the + mark remains and that the folder is still closed.
Also, if I click the + symbol this is what happend:
How can I solve this?

Well, finally I have to say that the official extjs documentation is quite poor for me. I found a solution by test and reading a lot of posts in several foros. I found a solution that might be helpful to others:
var rootNode = store.getRootNode();
for (var i = 0, l = records.length; i < l; i++) {
var x = records[i].data;
var child = { ... };
if (!child.idparent) {
rootNode.appendChild(child);
} else {
var parent = rootNode.findChild('idelement', child.idparent, true);
parent.appendChild(child);
}
if (!child.leaf) {
var node = store.findNode('idelement', child.idelement);
node.set('expanded', true);
}
}
rootNode.set('expanded', true);
That's it

Related

Isotope: Combined multiple checkbox and searchbox filtering

I'm trying to combine the Isotope multiple checkbox filtering with a searchbox.
I used the example with the checkbox filters from here and tried to implement the searchbox but with no luck.
Just the checkbox filtering works well. I think i'm close to the solution but my javascript skills are at a very beginner level.
I commented out the section of what i've tried to implement.
Thank you for some hints
// quick search regex
var qsRegex;
var $grid;
var filters = {};
var $grid = $('.grid');
//set initial options
$grid.isotope({
layoutMode: 'fitRows'
});
$(function() {
$grid = $('#grid');
$grid.isotope();
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
/*var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
var filterResult = function() {
return comboFilter && searchResult;
}*/
$grid.isotope({
filter: comboFilter //or filterResult
});
});
});
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, ));
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
threshold = threshold || 100;
return function debounced() {
clearTimeout(timeout);
var args = arguments;
var _this = this;
function delayed() {
fn.apply(_this, args);
}
timeout = setTimeout(delayed, threshold);
}
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).prop('checked', false);
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.parents('.option-set').find(selector).prop('checked', false);
}
}
I found the solution by myself, but i had to add a second function for returning the searchresult. Otherwise the search function is triggered only after using a checkbox or leaving the search box input field.
How could i avoid this redundand code?
JS:
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, 200));
$(function() {
$grid = $('#grid');
$grid.isotope({
filter: function() {
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return searchResult;
}
});
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$grid.isotope({
filter: function() {
var buttonResult = comboFilter ? $(this).is(comboFilter) : true;
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return buttonResult && searchResult;
}
});
});
});

How to merge REST call results in Angular app more efficiently

I have an Angular SPA running on a SharePoint 2013 page. In the code, I'm using $q to pull data from 10 different SharePoint lists using REST and then merging them into one JSON object for use in a grid. The code runs and outputs the intended merged data but it's leaky and crashes the browser after a while.
Here's the code in the service:
factory.getGridInfo = function() {
var deferred = $q.defer();
var list_1a = CRUDFactory.getListItems("ListA", "column1,column2,column3");
var list_1b = CRUDFactory.getListItems("ListB", "column1,column2,column3");
var list_2a = CRUDFactory.getListItems("ListC", "column4");
var list_2b = CRUDFactory.getListItems("ListD", "column4");
var list_3a = CRUDFactory.getListItems("ListE", "column5");
var list_3b = CRUDFactory.getListItems("ListF", "column5");
var list_4a = CRUDFactory.getListItems("ListG", "column6");
var list_4b = CRUDFactory.getListItems("ListH", "column6");
var list_5a = CRUDFactory.getListItems("ListI", "column7");
var list_5b = CRUDFactory.getListItems("ListJ", "column7");
$q.all([list_1a, list_1b, list_2a, list_2b, list_3a, list_3b, list_4a, list_4b, list_5a, list_5b])
.then(function(results){
var results_1a = results[0].data.d.results;
var results_1b = results[1].data.d.results;
var results_2a = results[2].data.d.results;
var results_2b = results[3].data.d.results;
var results_3a = results[4].data.d.results;
var results_3b = results[5].data.d.results;
var results_4a = results[6].data.d.results;
var results_4b = results[7].data.d.results;
var results_5a = results[8].data.d.results;
var results_5b = results[9].data.d.results;
var combined_1 = results_1a.concat(results_1b);
var combined_2 = results_2a.concat(results_2b);
var combined_3 = results_3a.concat(results_3b);
var combined_4 = results_4a.concat(results_4b);
var combined_5 = results_5a.concat(results_5b);
for(var i = 0; i < combined_1.length; i++){
var currObj = combined_1[i];
currObj["column4"] = combined_2[i].column4;
currObj["column5"] = combined_3[i].column5;
currObj["column6"] = combined_4[i].column6;
currObj["column7"] = combined_5[i].column7;
factory.newObjectArray[i] = currObj;
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
Here's the REST call in CRUDFactory:
factory.getListItems = function (listName, columns){
var webUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items?$select="+columns+"&$top=5000";
var options = {
headers: { "Accept": "application/json; odata=verbose" },
method: 'GET',
url: webUrl
};
return $http(options);
};
And then here's the controller bit:
$scope.refreshGridData = function(){
$scope.hideLoadingGif = false;
$scope.GridData = "";
GlobalFactory.getGridInfo()
.then(function(){
$scope.GridData = GlobalFactory.newObjectArray;
$scope.hideLoadingGif = true;
});
};
UPDATE 1: Per request, Here's the HTML (just a simple div that we're using angular-ui-grid on)
<div ui-grid="GridOptions" class="grid" ui-grid-selection ui-grid-exporter ui-grid-save-state></div>
This code starts by declaring some get calls and then uses $q.all to iterate over the calls and get the data. It then stores the results and merges them down to 5 total arrays. Then, because my list structure is proper and static, I'm able to iterate over one of the merged arrays and pull data from the other arrays into one master array that I'm assigning to factory.newObjectArray, which I'm declaring as a global in my service and using as my grid data source.
The code runs and doesn't kick any errors up but the issue is with (I believe) the "getGridInfo" function. If I don't comment out any of the REST calls, the browser uses 45 MB of data that doesn't get picked up by GC which is then compounded for each click until the session is ended or crashes. If I comment out all the calls but one, my page only uses 18.4 MB of memory, which is high but I can live with it.
So what's the deal? Do I need to destroy something somewhere? If so, what and how? Or does this relate back to the REST function I'm using?
UPDATE 2: The return result that the grid is using (the factory.newObjectArray) contains a total of 5,450 items and each item has about 80 properties after the merge. The code above is simplified and shows the pulling of a couple columns per list, but in actuality, I'm pulling 5-10 columns per list.
At the end of the day you are dealing with a lot of data, so memory problems are potentially always going to be an issue and you should probably consider whether you need to have all the data in memory.
The main goal you should probably be trying to achieve is limiting duplication of arrays, and trying to keep the memory footprint as low as possible, and freeing memory as fast as possible when you're done processing.
Please consider the following. You mention the actual number of columns being returned are more than your example so I have taken that into account.
factory.getGridInfo = function () {
var deferred = $q.defer(),
// list definitions
lists = [
{ name: 'ListA', columns: ['column1', 'column2', 'column3'] },
{ name: 'ListB', columns: ['column1', 'column2', 'column3'], combineWith: 'ListA' },
{ name: 'ListC', columns: ['column4'] },
{ name: 'ListD', columns: ['column4'], combineWith: 'ListC' },
{ name: 'ListE', columns: ['column5'] },
{ name: 'ListF', columns: ['column5'], combineWith: 'ListE' },
{ name: 'ListG', columns: ['column6'] },
{ name: 'ListH', columns: ['column6'], combineWith: 'ListG' },
{ name: 'ListI', columns: ['column7'] },
{ name: 'ListJ', columns: ['column7'], combineWith: 'ListI' },
],
// Combines two arrays without creating a new array, mindful of lenth limitations
combineArrays = function (a, b) {
var len = b.length;
for (var i = 0; i < len; i = i + 5000) {
a.unshift.apply(a, b.slice(i, i + 5000));
}
};
$q.all(lists.map(function (list) { return CRUDFactory.getListItems(list.name, list.columns.join()); }))
.then(function (results) {
var listResultMap = {}, var baseList = 'ListA';
// map our results to our list names
for(var i = 0; i < results.length; i++) {
listResultMap[lists[i].name] = results[i].data.d.results;
}
// loop around our lists
for(var i = 0; i < lists.length; i++) {
var listName = lists[i].name, combineWith = lists[i].combineWith;
if(combineWith) {
combineArrays(listResultMap[combineWith], listResultMap[listName]);
delete listResultMap[listName];
}
}
// build result
factory.newObjectArray = listResultMap[baseList].map(function(item) {
for(var i = 0; i < lists.length; i++) {
if(list.name !== baseList) {
for(var c = 0; c < lists[i].columns.length; c++) {
var columnName = lists[i].columns[c];
item[columnName] = listResultMap[list.name][columnName];
}
}
}
return item;
});
// clean up our remaining results
for (var i = 0; i < results.length; i++) {
delete results[i].data.d.results;
delete results[i];
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
I would suggest to add some sort of paging option... It's perhaps not a great idea to add all results to one big list.
Next i would suggest against ng-repeat or add a "track by" to the repeat function.
Check out: http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
Fiddler your queries, the issue is probably rendering all the elements in the dom... Which could be kinda slow ( investigate)

store data issue with generic grid rendered in tabs

I have a generic grid component.
on click of menu item corresponding grid is displayed in independent tabs.
on rendering the grid component, store data is set dynamically and grid is populated.
The problem if I open two grids in two tabs, on navigating to the first tab, grid data is not displayed as the store data is set to second grid data.
Hoping to find solution.Thank you
code in main controller:
OnMenuItemClick: function(c){
var nodeText = c.text,
tabs = Ext.getCmp('app-tab'),
tabBar = tabs.getTabBar(),
tabIndex;
for(var i = 0; i < tabBar.items.length; i++) {
if (tabBar.items.get(i).getText() === nodeText) {
tabIndex = i;
}
}
if (Ext.isEmpty(tabIndex)) {
/* Note: While creating the Grid Panel,here we are passing the Menu/Grid Id along with it for future reference */
tabs.add(Ext.create('DemoApp.view.grid.GenericGrid',{title:nodeText,gridId:c.id,overflowY: 'scroll',closable:true}));
tabIndex = tabBar.items.length - 1 ;
}
tabs.setActiveTab(tabIndex);
}
code in generic grid controller:
renderGridMetadata: function(genericGrid) {
var store = Ext.getStore("DemoApp.store.GenericGrid"),
gridId = genericGrid.up().gridId,
resourceURL = "resources/data/" + gridId + ".json";
var serviceInput = Util.createServiceResponse(gridId);
/*Dynamically add the proxy URL to the ViewModel
DemoApp.model.GenericGrid.getProxy().setUrl(resourceURL);*/
Ext.getBody().mask("Loading... Please wait...", 'loading');
Ext.Ajax.request({
url: Util.localGridService,
method: 'POST',
headers: {
"Content-Type": "application/json",
'SM_USER': 'arun.x.kumar.ap#nielsen.com',
'SM_SERVERSESSIONID': 'asdfadsf'
},
jsonData: {
getConfigurationAndDataRequestType: serviceInput
},
success: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
var data = Util.decodeJSON(conn.responseText);
/* Apply REST WebServices response Metadata to the Grid */
var recordsMetaData = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record;
var jsonMetaDataArray = [];
for (var c = 0; c < recordsMetaData.length; c++) {
var jsonMetaDataObject = {};
var text = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].displayName;
var dataIndex = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].columnName;
jsonMetaDataObject["text"] = text;
jsonMetaDataObject["dataIndex"] = dataIndex;
jsonMetaDataArray.push(jsonMetaDataObject);
}
/* Apply REST WebServices response data to the Grid */
var recordsData = data.getConfigurationAndDataReplyType.gridDataResponse.record;
var jsonDataArray = [];
for (var r = 0; r < recordsData.length; r++) {
var columnsData = data.getConfigurationAndDataReplyType.gridDataResponse.record[r].column;
var jsonDataObject = {};
for (var c = 0; c < columnsData.length; c++) {
jsonDataObject[columnsData[c].columnId] = columnsData[c].columnValue;
}
jsonDataArray.push(jsonDataObject);
}
store.setData(jsonDataArray);
genericGrid.reconfigure(store, jsonMetaDataArray);
},
failure: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
Util.showErrorMsg(conn.responseText);
}
});
store.load();
}
});
Most likely there is only one instance of DemoApp.store.GenericGrid.
Frankly, I only guess because I see that you call Ext.getStore("DemoApp.store.GenericGrid") that implies the store is declared in stores:["DemoApp.store.GenericGrid"] array probably in the application class.
If a store is declared this way then Ext automatically creates one instance of it setting storeId to the string listed in stores:[]. Hence, Ext.getStore() returns that instance.
If you want to have two independent instances of the grid you have to create store instances yourself preferably in initComponent override.

javascript: when declaring a prototype method: error is invalid left hand side for assignment

I am new to object oriented javascript. Trying to make an object constructor.
Here is my code
function Collection() {
this.ports = build_ports_collection();
this.all_things = build_things_collection();
this.added_things = function() {
this.added_things.total_added = 0;
var temp = this.all_things;
temp.splice($(sth).val(), 1);
this.added_things.all = temp;
};
};
Collection.ports.prototype.reload = function() {
Collection.ports = build_ports_collection();
};
Collection.all_things.prototype.reload = function() {
Collection.all_things = build_things_collection();
};
Collection.added_things.all.prototype.reload() = function() {
var temp = Collection.all_things;
temp.splice($(sth).val(), 1);
Collection.added_things.all = temp;
};
Collection.added_things.prototype.add_things = function() {
this.added_things.total_added++;
add_things();
};
Collection.added_things.prototype.remove_things = function() {
this.added_things.total_added--;
remove_things();
};
I am getting error in the line Collection.added_things.all.prototype.reload()=....
netbeans reports: invalid left hand side for assignment.
here my intention was to bind a method reload() to Collection.added_things.all so that it will be shared among all instances of Collection
What point i am missing ?
Not sure if this is the answer you're looking for, but this came to mind.
Collection.added_things.all.prototype.reload() = function() {
var temp = Collection.all_things;
temp.splice($(sth).val(), 1);
Collection.added_things.all = temp;
};
There, you are assigning stuff to the prototype of Collection.added_things.all, while
this.added_things = function() {
this.added_things.total_added = 0;
var temp = this.all_things;
temp.splice($(sth).val(), 1);
this.added_things.all = temp;
};
is the first to declare the .all on Collection.added_things - basically, you are trying to assign a value to a property/variable/pointer that does not exist until added_things is first called.

Delete multiple items from grid using CheckboxSelectionModel

Using ExtJs4.1 on Sencha Architect.
I have following code in my onDeleteButton code
onDeleteButtonClick: function(button, e, options) {
var active = this.activeRecord;
var myGrid = Ext.getCmp('publisherResultsGridView'),
sm = myGrid.getSelectionModel(),
selection = sm.getSelection(); // gives you a array of records(models)
if (selection.length > 0){
for( var i = 0; i < selection.length; i++) {
this.application.log('OnDeleteItemID is ' + selection);
}
this.remove(selection);
}
Code for Remove Function
remove: function(record) {
var store = Ext.getStore('PublisherProperties');
store.proxy.url = MasterDataManager.globals.url + "Publishers/";
store.remove(record);
store.sync();
When I run it, I could see an array of objects in my log, also I dont get any errors after the remove function is executed. But the store doesnt update, I mean it doesnt remove the selected items.
Can somebody please help me.
Thanks
I solved my problem by making the following changes.
To onDeleteButtonClick
if (selection.length > 0){
for( var i = 0; i < selection.length; i++) {
this.application.log('OnDeleteItemID is ' + selection[i].data.id);
this.remove(selection[i]);
}
}
To Remove function
remove: function(record) {
var store = Ext.getStore('PublisherProperties');
this.application.log('Remove Function is ' + record);
store.proxy.url = MasterDataManager.globals.url + "Publishers/" + record.data.id;
store.load({
scope : this,
callback : function(records, operation, success){
if (records.length > 0){
var store2 = Ext.getStore('PublisherProperties');
store2.proxy.url = MasterDataManager.globals.url + "Publishers/";
store2.remove(records[0]);
store2.sync();
}
}
});
//store.remove(record);
//store.sync();

Resources