Events with Cytoscapejs compound-drag-and-drop extension - cytoscape.js

I am using cytoscapejs and the extension compound-drag-and-drop. My aim is to shoot an event to my database when I drag a node and drop it over another. I am taking the id (of my future child node) with cdndtapstart or cdndout (when it is inside a compound node) and event.target._private.data.id, and then, with cdnddrop I call dropSibling._private.data.id, and with this data I can do my ajax call.
The problem that I have is that those events are acumulating one over another, if I drag the node once is fine, the second time that I drag it, it will produce two ajax call, the third time will give me three calls. Is there a way to avoid this or should it be reported as a bug?
cy.on('cdndout', 'node', function(event, dropTarget, dropSibling){
let type = event.target._private.data.type;
let id = event.target._private.data.id;
let gId = event.target._private.data;
if(type == 'device'){
cy.on('cdnddrop', function(event, dropTarget, dropSibling){
var typeDe = dropSibling._private.data
if(typeDe == undefined){
$.notify({message: err},{type: 'danger'});
createGraph()
} else {
let uuid = event.target._private.data.id;
let gId = dropSibling._private.data.id;
setResourceToGroup(uuid, gId, cb)
.then(reso => getAllResources())
.then(allReso => createGraph())
.catch(err => {
$.notify({message: parseLog(err)},{type: 'danger'});
createGraph()
})
}
})
}
})
So with this code, the ajax call that I have in the function setResourceToGroup, will be executed as many times as I drag the node. I am guessing I am not handling the events properly and they are accumulating... any help with that?

Events in cytoscape.js are quite simple, you bind an event and that event fires when the conditions of the binded event are met. The problems start, when you call the same binding operation twice or more. Then your event works normally, but the second you call that bind again, you have 2 events on your hand. And they will fire both at the same time! So how do you solve that?
Every time you call cy.bind() (cy.bind() is the same as cy.on()), you have to evaluate if that line can be executet more than once. If yes, then you have to do this:
cy.unbind('cdnout');
cy.bind('cdndout', 'node', function(event, dropTarget, dropSibling){
let type = event.target._private.data.type;
let id = event.target._private.data.id;
let gId = event.target._private.data;
if(type == 'device'){
cy.unbind('cdnddrop);
cy.bind('cdnddrop', function(event, dropTarget, dropSibling){
var typeDe = dropSibling._private.data
if(typeDe == undefined){
$.notify({message: err},{type: 'danger'});
createGraph()
} else {
let uuid = event.target._private.data.id;
let gId = dropSibling._private.data.id;
setResourceToGroup(uuid, gId, cb)
.then(reso => getAllResources())
.then(allReso => createGraph())
.catch(err => {
$.notify({message: parseLog(err)},{type: 'danger'});
createGraph()
});
}
});
}
});
By unbinding the event first, you can only have one event firing at once :)

Related

How to prevent closing of cell edit mode on validation errors with custom vue components in ag-grid

I have succesfully rendered my own component as the cellEditor and would like and on-leave I would like it to try to validate the value and prevent the closing if it fails.
If I look at this then https://www.ag-grid.com/javascript-grid-cell-editing/#editing-api there's cancelable callback functions for editing. But in this callback function is there a way to access the current instantiated component? I would think that would be the easiest way to handle this.
I'm using vee-validate so the validation function is async, just to keep in mind.
Use Full row editing.
Create a global variable like
var problemRow = -1;
Then Subscribe to this events:
onRowEditingStarted: function (event) {
if (problemRow!=-1 && event.rowIndex!=problemRow) {
gridOptions.api.stopEditing();
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
},
onRowEditingStopped: function (event) {
if (problemRow==-1) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
}
if (problemRow == event.rowIndex) {
if (event.data.firstName != "your validation") {
problemRow = event.rowIndex
gridOptions.api.startEditingCell({
rowIndex: problemRow,
colKey: 'the column you want to focus',
});
}
else{
problemRow=-1;
}
}
},
I had a similar issue - albeit in AngularJS and the non-Angular mode for ag-grid - I needed to prevent the navigation when the cell editor didn't pass validation.
The documentation is not very detailed, so in the end I added a custom cell editor with a form wrapped around the input field (to handle the niceties such as red highlighting etc), and then used Angular JS validation. That got me so far, but the crucial part was trying to prevent the user tabbing out or away when the value was invalid so the user could at least fix the issue.
I did this by adding a value parser when adding the cell, and then within that if the value was invalid according to various rules, throw an exception. Not ideal, I know - but it does prevent ag-grid from trying to move away from the cell.
I tried loads of approaches to solving this - using the tabToNextCell events, suppressKeyboardEvent, navigateToNextCell, onCellEditingStopped - to name a few - this was the only thing that got it working correctly.
Here's my value parser, for what it's worth:
var codeParser = function (args) {
var cellEditor = _controller.currentCellEditor.children['codeValue'];
var paycodeId = +args.colDef.field;
var paycodeInfo = _controller.paycodes.filter(function (f) { return f.id === paycodeId; })[0];
// Check against any mask
if (paycodeInfo && paycodeInfo.mask) {
var reg = new RegExp("^" + paycodeInfo.mask + '$');
var match = args.newValue.match(reg);
if (!match) {
$mdToast.show($mdToast.simple().textContent('Invalid value - does not match paycode format.').position('top right').toastClass('errorToast'))
.then(function(r) {
_controller.currentCellEditor.children['codeValue'].focus();
});
throw 'Invalid value - does not match paycode format.';
}
}
return true;
};
The _controller.currentCellEditor value is set during the init of the cell editor component. I do this so I can then refocus the control after the error has been shown in the toast:
CodeValueEditor.prototype.init = function (params) {
var form = document.createElement('form');
form.setAttribute('id', 'mainForm');
form.setAttribute('name', 'mainForm');
var input = document.createElement('input');
input.classList.add('ag-cell-edit-input');
input.classList.add('paycode-editor');
input.setAttribute('name', 'codeValue');
input.setAttribute('id', 'codeValue');
input.tabIndex = "0";
input.value = params.value;
if (params.mask) {
input.setAttribute('data-mask', params.mask);
input.setAttribute('ng-pattern','/^' + params.mask + '$/');
input.setAttribute('ng-class',"{'pattern-error': mainForm.codeValue.$error.pattern}");
input.setAttribute('ng-model', 'ctl.currentValue');
}
form.appendChild(input);
this.container = form;
$compile(this.container)($scope);
_controller.currentValue = null;
// This is crucial - we can then reference the container in
// the parser later on to refocus the control
_controller.currentCellEditor = this.container;
$scope.$digest();
};
And then cleared in the grid options onCellEditingStopped event:
onCellEditingStopped: function (event) {
$scope.$apply(function() {
_controller.currentCellEditor = null;
});
},
I realise it's not specifically for your components (Vue.js) but hopefully it'll help someone else. If anyone has done it a better way, I'm all ears as I don't like throwing the unnecessary exception!

Ionic 3 infinite-scroll simulate in e2e test jasmine/protractor

If you go here: http://ionicframework.com/docs/api/components/infinite-scroll/InfiniteScroll/
Inspect the demo and click the last item on the list:
Then in the console type: $0.scrollIntoView()
Infinite Scroll is never triggered.
Is there a way to programmatically trigger infinite-scroll in protractor context?
The implementation of the scroll in your example rely on the speed/velocity of the scroll which I guess falls far from the expected range when scrollIntoView is called.
One workaround is to simulates a smooth scroll by emitting multiple scroll events over a reasonable time. The idea is to reproduce as close as possible the behavior of a real user.
Some browsers already provides the option via scrollIntoView (supported by Chrome 62) :
$0.scrollIntoView({behavior: "smooth", block: "end"});
Using the accepted answer, in my case, I used ion-infinite-scroll as the argument.
Complete test to check if more content is loaded in Ionic:
describe('Scroll', () => {
it('should load more when reached end', async () => {
let list = getList();
let currentCount = await list.count();
const refresher = element(by.tagName('ion-infinite-scroll')).getWebElement();
let count = 0;
while(true){
browser.executeScript(`arguments[0].scrollIntoView({behavior: "smooth", block: "end"});`, refresher);
browser.sleep(1000); // wait for data to be loaded from api
list = getList();
let newCount = await list.count();
expect(newCount).toBeGreaterThanOrEqual(currentCount)
expect(newCount).toBeLessThanOrEqual(currentCount * 2)
if(newCount === currentCount){
break;
}
currentCount = newCount;
count++;
}
expect(count).toBeGreaterThan(0);
})
});
function getList() {
return element(by.className(pageId + ' list')).all(by.tagName('ion-item'));
}

Chartist.js and events

I am trying to add click events on the graphs that I am rendering. From chart.click to chart.on('click', function (e){ }).
What I am trying to do is allow the user to select points on the graph and for me to now what selections the user made. Is that at all possible using chartist.js?
I read through the documentation: CHARTIST.JS
My code:
if (item.GraphType.Description == "Line") {
var chart = new Chartist.Line(
container[0],
{
labels: d.Labels,
series: d.SeriesData
},
{
axisY: {
offset: 60
}
}
);
chart.click(function (e) {
console.log(e);
});
}
It is entirely possible, yes. Chartist renders SVG nodes to the page, so using a library like jQuery you can easily find all nodes that you want and attach events to them. You can be as specific or broad in the nodes you're looking for to only attach events to very specific nodes or elements on the chart.
For completeness sake, here is a short example of how to attach events that log the value of a data point when clicked upon to the console using jQuery:
$('.ct-chart-line .ct-point').click(function () {
var val = $(this).attr("ct:value");
console.log(val);
});
You should, however, make sure that the events attach only when the chart is created or drawn if you want to ensure the data points are on the page, which can be triggered by the "created" or "draw" events:
var chart = new Chartist.Line(...);
// attach an event handler to the "created" event of the chart:
chart.on("created", function () {
// attach the necessary events to the nodes:
$('.ct-chart-line .ct-point').click(function () {
var val = $(this).attr("ct:value");
console.log(val);
});
});

backbone view in router lost after creation

When I try to associate my router's public variable this.currentView to a newly created view, the view gets lost, the public variable is null instead of containing the newly created view.
var self=this;
var watchListsCollection = new WatchlistCollection;
watchListsCollection.url = "watchlists";
user.fetch().done(function() {
watchListsCollection.fetch().done(function () {
loggedUser.fetch().done(function () {
self.currentView = new UserView(user, watchListsCollection,loggedUser);
});
});
});
alert(this.currentView); //null
The fetch() calls you do are firing asynchronous AJAX requests, meaning the code in your done handlers are not going to be executed untill the server calls return. Once you've executed user.fetch() the browser will fire off a request and then continue running your program and alert this.currentView without waiting for the requests to finish.
The sequence of events is basically going to be
call user.fetch()
alert this.currentView
call watchListsCollection.fetch()
call loggedUser.fetch()
set the value of self.currentView
You will not be able to see the value of your currentView before the last server request have completed.
If you change your code to
var self=this;
var watchListsCollection = new WatchlistCollection;
watchListsCollection.url = "watchlists";
user.fetch().done(function() {
watchListsCollection.fetch().done(function () {
loggedUser.fetch().done(function () {
self.currentView = new UserView(user, watchListsCollection,loggedUser);
alertCurrentView();
});
});
});
function alertCurrentView() {
alert(this.currentView);
}
You should see the correct value displayed. Now, depending on what you intend to use your this.currentView for that might or might not let you fix whatever issue you have, but there's no way you're not going to have to wait for all the requests to complete before it's available. If you need to do something with it straight away you should create your UserView immediately and move the fetch() calls into that view's initialize().
fetch() is asynchronous, but you check your variable right after you've started your task. Probably these tasks, as they supposed to be just reads, should be run in parallel. And forget making a copy of this, try _.bind instead according to the Airbnb styleguide: https://github.com/airbnb/javascript
var tasks = [];
tasks.push(user.fetch());
tasks.push(watchListsCollection.fetch());
tasks.push(loggedUser.fetch());
Promise.all(tasks).then(_.bind(function() {
this.currentView = new UserView(user, watchListsCollection, loggedUser);
}, this));
or using ES6 generators:
function* () {
var tasks = [];
tasks.push(user.fetch());
tasks.push(watchListsCollection.fetch());
tasks.push(loggedUser.fetch());
yield Promise.all(tasks);
this.currentView = new UserView(user, watchListsCollection, loggedUser);
}

angular-scenario e2e testing - waiting for key events to complete before proceeding

How are people writing angular e2e tests that involve triggering a sequence of UI events? The async nature of scenario seems to make it difficult.
details:
I'm writing tests for an app that has a lot of key handling to help speed editing of a specialised form. I've pulled together a keyboard extension to the scenario dsl (see below) but only the first key event of a test has any effect. i.e.
keyboard().keydown(null, 'keydown', 40, false, true); // ctrl-down
expect(element('*:focus').text()).toEqual('00:04');
keyboard().keydown(null, 'keydown', 40, false, true); // ctrl-down
expect(element('*:focus').text()).toEqual(''); // but equals 00:04
The second keydown doesn't do anything, because it doesn't find a *:focus to route the key to (although there is one on the screen). Confusing.
angular.scenario.dsl('keyboard', function() {
var chain = {};
chain.keydown = function(selector, keyEvent, keyCode, shift, ctrl) {
return this.addFutureAction("keyEvent", function($window, $document, done) {
var jQuery = $window.$;
var e = jQuery.Event(keyEvent);
e.keyCode = keyCode; // # Some key code value
e.altKey = false;
e.ctrlKey = ctrl;
e.shiftKey = shift;
if (selector == null) selector = '*:focus';
var j = jQuery(selector);
if (j == null) j = jQuery('body');
j.trigger(e);
done();
});
};
return function() {
return chain;
};
});
User seem to have abandoned this question, but as I said, this is probably an issue with his keydown event handler.
Made a Plnker here with exactly the same code and everything work as expected.