Expand node not calling callback - extjs

I am testing my ExtJs App with Jasmine. So there are no views involved.
I want to expand several nodes, but first my root node. But even expanding that node fails.
I create my TreeStore, then:
Code:
// oStore is my treestore, everything OK
// Here, I also tried calling oStore.load(); see below
var oNode = oStore.getNodeById( 'root' );
// oNode.isExpanded() says false
// oNode.hasChildNodes() says false
oNode.expand(false, function(oChildren) {
// it never gets here
console.log( "hello?");
});
My listener for load gets called, but the listener for beforeexpand does not get called.
If I call oStore.load() at the beginning after store creation, then when the on load listener gets called it says, oNode.childNodes.length has 3 children...
So why is expand()'s callback not called? How can I get that node to expand?
Why are the children of the node already loaded when calling oStore.load()? After that expand() is also not fired.
EDIT:
Starting my root node with expanded: true makes my store collapse correctly on collapse(), but after it expand() does nothing.
oNode.collapse(false, function() {
console.log( "collapse()" ); // works, but expand() afterwards does not
});

Found the solution. I need to wait for the store to get loaded. Is is a Jasmine issue:
runs( function() {
oStore.on( 'load', function() {
bStoreLoaded = true;
});
});
waitsFor( function() {
return bStoreLoaded;
}, " store to be loaded", 5000 );
runs( function() {
oNode.expand(false, function( aoChildren ) {
aoChildrenRoot = aoChildren;
bRootExpanded = true;
});
});

There is some convoluted logic in the source to tell the node whether or not it needs to expand or be expandable. Take a look at the code below that I ended up resorting to when I tried to manipulate the tree programmatically:
if (!parentNode.isExpanded() && !parentNode.isLeaf()) {
parentNode.expand(false, function () {// deal with open or closed paths
console.log('expanded parent to pick up new item');
});
} else {
parentNode.callStore('suspendAutoSync');
if (parentNode.isLeaf()) { // Parts that are leafs
parentNode.set("leaf", false); //must be set to work properly
parentNode.appendChild(newPart);
parentNode.expand(); //expand to show newly created child
} else {
parentNode.insertChild(0, newPart);
}
parentNode.callStore('resumeAutoSync');
}

Related

UI-grid saveState service circular logic

Here is a summary of the problem: I set up a column sortChange() listener, which responds to sort changes by firing off a query to fetch newly sorted data. I save the grid state before the fetch, and restore the grid state after the fetch. The problem is that the restore gridState mechanism triggers the original sort listener, causing the whole process to start over again, and again, and again.
scope.sitesGrid.onRegisterApi = function(gridApi) {
scope.gridApi = gridApi;
scope.gridApi.core.on.sortChanged(scope, function () {
// load new sites on a sort change
scope.initialize();
});
};
scope.initialize = function() {
// save current grid state
scope.gridApi && (scope.gridState = scope.gridApi.saveState.save());
fetchSites().then(function (sites) {
scope.sitesGrid.data = sites
// restore current grid state, but inadvertently retrigger the 'sortChanged' listener
scope.gridApi.saveState.restore(scope,scope.gridState);
})
};
I was thinking that I could set up a click listener on each column header, instead of using a sortChange listener, however this solution seems ugly and requires going into every header cell template and making changes.
How about some kind of scope variable to track the loading of data?
scope.gridApi.core.on.sortChanged(scope, function () {
if (!scope.isLoading) {
scope.initialize();
}
});
and
fetchSites().then(function (sites) {
scope.isLoading = true;
scope.sitesGrid.data = sites;
scope.gridApi.saveState.restore(scope,scope.gridState);
scope.isLoading = false;
})
You might need to add some timeout() calls in places if there are timing issues with this. Creating a Plunker to demonstrate this would help in that case.
I think i find solution. I created restore function in my directive (u can use it where you want). I just block executing next iteration until action is finished.
function restoreState() {
if ($scope.gridState.columns !== undefined && !isRestoring) { //check is any state exists and is restored
isRestoring = true; //set flag
$scope.gridApi.saveState.restore($scope, $scope.gridState)
.then(function () {
isRestoring = false; //after execute release flag
});
}
}
function saveState() {
if (!isRestoring) {
$scope.gridState = $scope.gridApi.saveState.save();
}
}

angular `$broadcast` issue - how to fix this?

In my app, I am boradcasting a event for certain point, with checking some value. it works fine But the issue is, later on whenever i am trigger the broadcast, still my conditions works, that means my condition is working all times after the trigger happend.
here is my code :
scope.$watch('ctrl.data.deviceCity', function(newcity, oldcity) {
if (!newcity) {
scope.preloadMsg = false;
return;
}
scope.$on('cfpLoadingBar:started', function() {
$timeout(function() {
if (newcity && newcity.originalObject.stateId) { //the condition not works after the first time means alwasy appends the text
console.log('each time');
$('#loading-bar-spinner').find('.spinner-icon span')
.text('Finding install sites...');
}
}, 100);
});
});
you can deregister the watcher by storing its reference in a variable and then calling it:
var myWatch = scope.$watch('ctrl.data.deviceCity', function(){
if( someCondition === true ){
myWatch(); //deregister the watcher by calling its reference
}
});
if you want to switch logic, just set some variable somewhere that dictates the control flow of the method:
var myWatch = scope.$watch('ctrl.data.deviceCity', function(){
scope.calledOnce = false;
if(!scope.calledOnce){
//... run this the first time
scope.calledOnce = true;
}
else {
// run this the second time (and every other time if you do not deregister this watch or change the variable)
// if you don't need this $watch anymore afterwards, just deregister it like so:
myWatch();
}
})

extjs treepanel load children without expand

I use Extjs 3.4. I am working on TreePanel with checkbox solution.
What I need is: When I check father node, all childNodes also checked. It's easy, but it depends on extjs expand all childNodes.
If I do
tree.expandAll();
tree.collapseAll();
My check strategy will work, but I don't want the expand effect.
My extjs code(checkchange event) is something like the following:
var checkchange = function(node, flag) {
if (node.hasChildNodes()) {
node.cascade(function(node) {
node.attributes.checked = flag;
node.ui.checkbox.checked = flag;
return true;
});
}
var pNode = node.parentNode;
for (; pNode != null; pNode = pNode.parentNode) {
if (flag || tree.getChecked("checked", pNode).length - 1 == 0) {
pNode.attributes.checked = flag;
pNode.ui.checkbox.checked = flag;
}
}
};
var tree = new Ext.tree.TreePanel({
listeners: {
'checkchange': checkchange
},
})
How can I do? Thank every one for giving advice.
[ EDIT ]
I create A Demo In jsfiddle, that can be easily test.
(Since Extjs 3.4.0 cdn used by jsfiddle not work, I append another cdn extjs resource from https://cdnjs.com/libraries/extjs/3.4.1-1)
I am not sure whether you really want the whole tree to be loaded node by node when checking the root node. I would recommend to lazily check the child nodes when they are loaded for an already-checked parent node, by attaching to the load event. Something like this:
load:function(me, node) {
if(node && node.attributes.checked) node.cascade(
... [function to check all children]
)
}
Depending on your intentions for further processing and your tree size, this could be better than expanding the whole tree to render and check all checkboxes.
If you want the tree to be loaded directly, I would recommend to use preloadChildren:true on the TreeLoader. This is easier than a manual implementation of cascaded load.
I didn't really solve this problem. But I got an eclectic solution.
Only expand when needed
checkchange : function(node, flag){
node.cascade(function(node) {
// when you check, first expand, then child nodes can be checked too
if(node.expanded == false)
node.expand(true);
node.attributes.checked = flag;
node.ui.checkbox.checked = flag;
return true;
});
......
}
This will meet the precondition that all child nodes should have expanded. But also no need expanded when first loaded.
If a parent node checked when first loaded, all child nodes need to be expand
this.treeLoader = new Ext.tree.TreeLoader({
url : 'xxx',
baseParams : {
someparam: ""
},
listeners : {
'load' : function(tree,node,response) {
var res = Ext.util.JSON.decode(response.responseText);
if(res.success != undefined && !res.success) {
Ext.Msg.alert('Hint', res.message);
return;
}
node.cascade(function(node) {
if(node.attributes.checked == true) {
node.expand(true);
}
});
},
}
});
This two methods does solve my prolem though not very perfect.
Hope this can help others.

tell Protractor to wait for the page before executing expect

When I click the export button, it makes a REST call to our endpoint then few seconds after, I receive the response then I also render the table. Unfortunately, I read that every call is asynchronous which means my expect will be executed even if table hasn't been rendered yet. The expect I wrote checks if the string is on the table but it's failing since it's not there yet. What is the proper approach to this?
it('should generate global user report', function() {
element(by.css('button#exportButton')).click();
expect(element(by.css("th[name*=Date]")).getText()).
toEqual('Date');
})
The error on the console is
NoSuchElementError: No element found using locator: By.cssSelector("th[name*=Date]")
I noticed that the table hasn't been rendered yet that's why it's failing.
Protractor 1.7 introduced a feature called "Expected Conditions", that can be applied here.
Wait for element to become visible:
var EC = protractor.ExpectedConditions;
var elm = element(by.css("th[name*=Date]"));
browser.wait(EC.visibilityOf(elm), 5000);
expect(elm.getText()).toEqual('Date');
I had problem waiting for a dynamic element to appear. Have the driver wait for it to either be present or displayed. The number at the end is the timeout.
element(by.css('button#exportButton')).click();
var header = element(by.css("th[name*=Date]"));
browser.driver.wait(function() {
return header.isPresent();
}, 1000);
expect(header.getText()).toEqual('Date');
I had to wait until it was present AND displayed before the test was fully stable. You can do that like this:
var header = element(by.css("th[name*=Date]"));
browser.driver.wait(function() {
return header.isPresent().then(function(present) {
if (present) {
return header.isDisplayed().then(function(visible) {
return visible;
});
} else {
return false;
}
});
}, 1000);

How to get access to a window that is loaded into a panel

I'm loading an external script (that creates a new window component) into a panel, which works fine.
Now, I want to access the created window from a callback function to register a closed event handler. I've tried the following:
panel.load({
scripts: true,
url: '/createWindow',
callback: function(el, success, response, options) {
panel.findByType("window")[0].on("close", function { alert("Closed"); });
}
});
However, the panel seems to be empty all the time, the findByType method keeps returning an empty collection. I've tried adding events handlers for events like added to the panel but none of them got fired.
I don't want to include the handler in the window config because the window is created from several places, all needing a different refresh strategy.
So the question is: how do I access the window in the panel to register my close event handler on it?
The simplest solution would be to simply include your close handler in the window config that comes back from the server using the listeners config so that you could avoid having a callback altogether, but I'm assuming there's some reason you can't do that?
It's likely a timing issue between the callback being called (response completed) and the component actually getting created by the ComponentManager. You might have to "wait" for it to be created before you can attach your listener, something like this (totally untested):
panel.load({
scripts: true,
url: '/createWindow',
callback: function(el, success, response, options) {
var attachCloseHandler = function(){
var win = panel.findByType("window")[0];
if(win){
win.on("close", function { alert("Closed"); });
}
else{
// if there's a possibility that the window may not show
// up maybe add a counter var and exit after X tries?
attachCloseHandler.defer(10, this);
}
};
}
});
I got it to work using a different approach. I generate a unique key, register a callback function bound to the generated key. Then I load the window passing the key to it and have the window register itself so that a match can be made between the key and the window object.
This solution takes some plumbing but I think its more elegant and more reliable than relying on timings.
var _windowCloseHandlers = [];
var _windowCounter = 0;
var registerWindow = function(key, window) {
var i;
for (i = 0; i < _windowCounter; i++) {
if (_windowCloseHandlers[i].key == key) {
window.on("close", _windowCloseHandlers[i].closeHandler);
}
}
};
var loadWindow = function(windowPanel, url, params, callback) {
if (params == undefined) {
params = { };
}
windowPanel.removeAll(true);
if (callback != undefined) {
_windowCloseHandlers[_windowCounter] = {
key: _windowCounter,
closeHandler: function() {
callback();
}
};
}
Ext.apply(params, { windowKey: _windowCounter++ });
Ext.apply(params, { containerId: windowPanel.id });
windowPanel.load({
scripts: true,
params: params,
url: url,
callback: function(el, success, response, options) {
#{LoadingWindow}.hide();
}
});
};
Then, in the partial view (note these are Coolite (Ext.Net) controls which generate ExtJs code):
<ext:Window runat="server" ID="DetailsWindow">
<Listeners>
<AfterRender AutoDataBind="true" Handler='<%# "registerWindow(" + Request["WindowKey"] + ", " + Detailswindow.ClientID + ");" %>' />
</Listeners>
</ext:Window>
And finally, the window caller:
loadWindow(#{ModalWindowPanel}, '/Customers/Details', {customerId: id },
function() {
#{MainStore}.reload(); \\ This is the callback function that is called when the window is closed.
});

Resources