Drag an event in fullCalendar component with a specific duration - drag-and-drop

I've seen the solution to drag and drop external events in fullcalendar. But, in this demo, all the external events have a duration of 2 hours (because defaultEventMinutes parameter is set to 120). I'm trying to change this demo in order to manage events with different durations. Say, "My event 1" is 45min long, "My event 2" is 165min, etc.
At the beginning I though there may be an attribute to store the duration in the eventObject, but according to the documentation, it's not the case.
Then, I thought it would be possible to change the value of 'defaultEventMinutes' when starting dragging the event. But apparently, I can't do it without rebuilding the whole calendar.
According to you, what is the best means to meet this requirement?
Thanks in advance for your advice...

Worked on this as well and have solved the duration shown on fullCalendar this way:
Having a custom "setOptions" function for fullCalendar.
Having a property for fullCalendar called "dragMinutes" that can be set during elements $(this).draggable({start:...}).
Here is the code for the custom setOptions:
...
function Calendar(element, options, eventSources) {
var t = this;
// hack for setting options that updates
function setOptions(new_options, refresh) {
$.extend(options, new_options);
if (refresh) {
var viewName = currentView.name;
changeView(viewName, true);
}
}
// exports ...
t.setOptions = setOptions;
...
Heres the code for handling "dragMinutes" option in fullCalendar:
/* External Dragging
--------------------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function (cell) {
clearOverlays();
if (cell) {
if (cellIsAllDay(cell)) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
} else {
var d1 = cellDate(cell);
if (opt('dragMinutes'))
var d2 = addMinutes(cloneDate(d1), opt('dragMinutes'));
else
var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
renderSlotOverlay(d1, d2);
}
}
}, ev);
}
And heres how i make event draggable and update the "dragMinutes":
// make the event draggable using jQuery UI
$(this).draggable({
containment: 'document',
// return a custom styled elemnt being dragged
helper: function (event) {
return $('<div class="uv-planning-dragging"></div>').html($(this).html());
},
opacity: 0.70,
zIndex: 10000,
appendTo: 'body',
cursor: 'move',
revertDuration: 0,
revert: true,
start: function (e, ui) {
// set the "dragMinutes" option in fullCalendar so shown interval about to be added is correct.
var data = $(this).data('eventObject');
if (data) {
var min = data.jsonProps.durationMsec / 1000 / 60;
if (macroCalendar.calendar) {
macroCalendar.calendar.fullCalendar('setOptions', { dragMinutes: Math.round(min) }, false);
}
}
},
stop: function (e, ui) {
// further process
}
});
Hope it helps.

If anyone still visits the thread and don't find the solution, the solution would be to set the duration parameter in event div... and then call draggable on that div.
$(this).data('event', {
title: 'new event title', // use the element's text as the event title
id: $(this).attr('id'),
stick: true, // maintain when user navigates (see docs on the renderEvent method)
duration: '03:00:00' // will set the duration during drag of event
});

Currently, the best solution I have found is adding a duration attribute on my event Object, then the code to create my fullCalendar looks like this:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
// HERE I force the end date based on the start date + duration
copiedEventObject.end = new Date(date.getTime() + copiedEventObject.duration * 60 * 1000);
copiedEventObject.allDay = allDay;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
});
The only drawback is when you're dragging the event, the event duration looks like defaultEventMinutes and not the actual duration, but I don't know how to fix it

These special properties can either be specified in the provided event object, or they can be standalone data attributes:
<!-- DURATION OF 3 hours EVENT WILL PROPAGATE TO CALENDAR WHEN DROPPED -->
<div class='draggable' data-event='1' data-duration='03:00' />
https://fullcalendar.io/docs/dropping/eventReceive/

With the latest fullcalendar v2.0.2, if you want the overlay to be of the particular duration, you can update in this function of fullcalendar-arshaw.js
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
var seconds = duration_in_minutes * 1000 * 60 ;
// we need to pass seconds into milli-seconds
if (d1.hasTime()) {
d2.add(seconds);
renderSlotOverlay(d1, d2, cell.col);
}
else {
d2.add(calendar.defaultAllDayEventDuration);
renderDayOverlay(d1, d2, true, cell.col);
}
}
}, ev);
}
Here, pass your duration in the external events object and that object you can fetch in _dragElement and then convert it into milli-seconds and pass it in d2.add(seconds). This will create the shadow of that mili-seconds on that calendar.

For non-external events you can use the fullcalendar settings:
defaultTimedEventDuration: (hours+':00:00'),
forceEventDuration: true,
// defaultEventMinutes: hours*60, // not needed
and in the event data you do not set the end property (or you null it):
eventData = {
title: title,
start: start,
// end: end, // MUST HAVE no end for fixedduration
color: '#00AA00',
editable: true, // for dragging
};
Ref: http://fullcalendar.io/docs/event_data/defaultTimedEventDuration/
Tip: In case you want to prevent the resizing of the events which is possible due to editable: true, you can use CSS to hide the handle: .fc-resizer.fc-end-resizer { display:none; }

Since v4 some of the above options are not working at all. The problem i was facing was as follows:
All day items for me have a duration, but not a start time. When i select a start time by dragging, the start time is set but as soon as i set the end date ( which is done similar as above answers ), the end date is reset again.. there is something buggy going on in the setDate function... the end date is set, this part works, then it does a comparisson on itself to find out the time difference between the dates, but the date is already set by the system itself causing the difference to be 0 which is causing the enddate to be set to null again......
A giant pain in my neck i got to say... it works perfect when staying within the timeline, but that's about it.
I managed to 'fix', more like destroy it by using this line in the eventDrop event, but it will also work in any other events you may use:
update your event with ajax here, since you have the start and end date *
calendar.refetchEvents(); in the success function
This is going to refetch all the events, it sounds pretty killer for performance but it doesn't seem to take up much time, try it for yourself.
This way my titles, times etc are always up to date and the calendar is showing the right end date.

Related

Is there a onScroll event for ag-grid

I am looking for a scroll event on ag-grid, I want to know when the scroll reaches the end and load the next set of rows, I know if you set the infinite scroll mode then ag-grid calles the getRows method, but in my application I do not get the next set of rows right away, I make a call to the server and server sends a separate message to the client with the new set of rows
After getting in deep, I found the perfect solution to this problem.
Please note here I am used AngularJS, But very easy to understand.
onBodyScroll:function(params) {
var bottom_px = $scope.gridOptions.api.getVerticalPixelRange().bottom;
var grid_height = $scope.gridOptions.api.getDisplayedRowCount() * $scope.gridOptions.api.getSizesForCurrentTheme().rowHeight;
if(bottom_px == grid_height)
{
alert('Bottom')
}
},
There's a grid event called 'onBodyScroll' which you can attach an event handler to it.
This event is somewhat secret as it was not there on their GridOptions type before version 18, even though it does work.
see this comment: https://github.com/ag-grid/ag-grid-enterprise/issues/89#issuecomment-264477535
They do have this event in document tho: https://www.ag-grid.com/javascript-grid-events/#miscellaneous
BodyScrollEvent
bodyScroll - The body was scrolled horizontally or vertically.
onBodyScroll = (event: BodyScrollEvent) => void;
interface BodyScrollEvent {
// Event identifier
type: string;
api: GridApi;
columnApi: ColumnApi;
direction: ScrollDirection;
left: number;
top: number;
}
You should be able to do that thing (loading the data from the server) as per below example.
First of all, define your dataSource.
const dataSource: IServerSideDatasource = {
getRows: (params: IServerSideGetRowsParams) => this._getRows(params, [])
};
this.gridApi.setServerSideDatasource(dataSource);
Declare _getRows method like this.
private _getRows(params: IServerSideGetRowsParams, data: any[]) {
this.gridApi.showLoadingOverlay();
service.getData(params) // the payload your service understands
.subscribe((result: any[]) => {
params.successCallback(result, -1);
params.failCallback = () => console.log('some error occured while loading new chunk of data');
this.gridApi.hideOverlay();
},
error => this._serverErrorHandler(error)
);
}
This is pretty much self-explanatory. Let's me know if anything is unclear to you.
BTW, I've used typescript for the example, javascript example would be kind of the same for ag-grid-react

Having trouble attaching event listener to a kml layer's polygon

Using Google Earth I have a loaded kml layer that displays polygons of every county in the US. On click a balloon pop's up with some relevant info about the state (name, which state, area, etc) When a user clicks the polygon I want the information to also pop up on a DIV element somewhere else.
This is my code so far.
var ge;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
ge.getNavigationControl().setStreetViewEnabled(true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
//here is where im loading the kml file
google.earth.fetchKml(ge, href, function (kmlObject) {
if (kmlObject) {
// show it on Earth
ge.getFeatures().appendChild(kmlObject);
} else {
setTimeout(function () {
alert('Bad or null KML.');
}, 0);
}
});
function recordEvent(event) {
alert("click");
}
// Listen to the mousemove event on the globe.
google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);
}
function failureCB(errorCode) {}
google.setOnLoadCallback(init);
My problem is that when I change ge.getGlobe() to kmlObject or ge.getFeatures() it doesn't work.
My first question is what should I change ge.getGlobe() to to be able to get a click listener when a user clicks on a kml layer's polygon?
After that I was planning on using getDescription() or getBalloonHtml() to get the polygons balloons information. Am I even on the right track?
...what should I change ge.getGlobe() to...
You don't need to change the event object from GEGlobe. Indeed it is the best option as you can use it to capture all the events and then check the target object in the handler. This means you only have to set up a single event listener in the API.
The other option would be to somehow parse the KML and attach specific event handlers to specific objects. This means you have to create an event listener for each object.
Am I even on the right track?
So, yes you are on the right track. I would keep the generic GEGlobe event listener but extend your recordEvent method to check for the types of KML object you are interested in. You don't show your KML so it is hard to know how you have structured it (are your <Polygon>s nested in <Placemarks> or ` elements for example).
In the simple case if your Polygons are in Placemarks then you could just do the following. Essentially listening for clicks on all objects, then filtering for all Placmark's (either created via the API or loaded in via KML).
function recordEvent(event) {
var target = event.getTarget();
var type = target.getType();
if(type == "KmlPolygon") {
} else if(type == "KmlPlacemark") {
// get the data you want from the target.
var description = target.getDescription();
var balloon = target.getBalloonHtml();
} else if(type == "KmlLineString") {
//etc...
}
};
google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);
If you wanted to go for the other option you would iterate over the KML Dom once it has loaded and then add events to specific objects. You can do this using something like kmldomwalk.js. Although I wouldn't really recommend this approach here as you will create a large number of event listeners in the api (one for each Placemark in this case). The up side is that the events are attached to each specific object from the kml file, so if you have other Plaemarks, etc, that shouldn't have the same 'click' behaviour then it can be useful.
function placeMarkClick(event) {
var target = event.getTarget();
// get the data you want from the target.
var description = target.getDescription();
var balloon = target.getBalloonHtml();
}
google.earth.fetchKml(ge, href, function (kml) {
if (kml) {
parseKml(kml);
} else {
setTimeout(function () {
alert('Bad or null KML.');
}, 0);
}
});
function parseKml(kml) {
ge.getFeatures().appendChild(kml);
walkKmlDom(kml, function () {
var type = this.getType();
if (type == 'KmlPlacemark') {
// add event listener to `this`
google.earth.addEventListener(this, 'click', placeMarkClick);
}
});
};
Long time since i have worked with this.. but i can try to help you or to give you some tracks...
About your question on "google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);"
ge.getGlobe can not be replaced with ge.getFeatures() : if you look in the documentation ( https://developers.google.com/earth/documentation/reference/interface_g_e_feature_container-members) for GEFeatureContainer ( which is the output type of getFeatures() , the click Event is not defined!
ge.getGlobe replaced with kmlObject: waht is kmlObject here??
About using getDescription, can you have a look on the getTarget, getCurrentTarget ...
(https://developers.google.com/earth/documentation/reference/interface_kml_event)
As I told you, i haven't work with this since a long time.. so I'm not sure this can help you but at least, it's a first track on which you can look!
Please keep me informed! :-)

Is there any event handler in EXTJS Paging Toolbar's Buttons?

I am new with EXTJS 4 and this forum. Sorry if it's already discussed in another thread, but I didn't found it.
My question is, I want my Grid Panel with Pagination to update it's store every 10 seconds. I have found a solution using userStore.loadPage(current_page), but it has a problem.
Some time, updating Grid Panel nearly in same time with user click "next" or "prev" in Pagination. This make Grid Panel to not working properly. What I want is, when I click "next" or "prev" or "refresh", the previous request (userStore.loadPage(current_page)) is aborted. So it will not interfere my current request.
But I didn't found event in EXTJS Paging Toolbar to handle "next", "prev", or "refresh" button. What is the solution for this issue? Is there any way?
This is my code just for reference:
// create User Store
var userStore = Ext.create('Ext.data.Store', {
model: 'EDC',
autoLoad: true,
pageSize: 10,
proxy: {
type: 'ajax',
url : 'Monitoring', // it is using Java servlet, so I write it this way
reader: {
type: 'json',
root: 'edc',
totalProperty: 'total'
}
}
});
// create Grid Panel
Ext.create('Ext.grid.Panel', {
store: userStore,
width: 800,
height: 400,
columns: [
{
text: "ID",
width: 50,
dataIndex: 'id'
},
{
text: 'Serial Number',
flex: 1,
dataIndex: 'sn'
}
// etc...
],
dockedItems: [{
xtype: 'pagingtoolbar',
store: userStore,
dock: 'bottom',
displayInfo: true
}]
});
It is how it is updated every 10 seconds
// after on Ready, reload every 10 seconds
Ext.onReady(function(){
self.setInterval("reloadCurrentEdc()", 10000);
});
// function for update
function reloadCurrentEdc(){
if(typeof userStore != 'undefined'){
userStore.loadPage(userStore.currentPage);
}
}
I think your problem is that your 'auto load' and your 'manual load' are so close together that your grid handles the result coming back from the first request as the second one.
I do agree with Alshten that the best way is to avoid requests that are so close together, you can do this by disabling the store load when there is already a store load in progress. but if you want your functionality I think you can do something like this:
listen to beforeload( Ext.data.Store store, Ext.data.Operation operation, Object eOpts ) event on the store, save the eOpts; listen to load( Ext.data.Store this, Ext.util.Grouper[] records, Boolean successful, Ext.data.Operation operation, Object eOpts ) compare the eOpts with the one you saved, if they are not the same, you know it's not the results you want.
You can have a look to the documentation about the paging toolbar component :
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.toolbar.Paging
There is a change which is fired every time the current page is changed, so it will be fired for "next" and "prev" click events. I haven't tried but I think it may be fired for "refresh" as well.
In my view, the best design would be to disable the buttons of the paging toobar (using the disable() function of this component) while the automatic reload is loading.
I use this selector: "gridpanel pagingtoolbar #refresh".
I'm able to use in my Controller classes in the init method mostly.
You can replace gridpanel with the alias or itemid of your grid.
.
.
.
init: function() {
this.control({
'gridpanel pagingtoolbar #refresh':{
click:function(){
console.log('grid panel', arguments);
}
}
});
},
.
.
.
Use
beforehange: function (tbar, pageData, eOpts) {
// here you can load data from server and load the data to store
return false // will avoid triggering store events
}
pageData is the page number
all button clicks like next/prev/refresh will trigger this function

jQuery event trigger; callback and timing with respect to animations

Perhaps my question deviates from the simplicity of itself: Given I .trigger() an event, how can I ensure that code following said .trigger() will not execute until the entire event handler function has completed, including all animations, delays, et al., therein?
I hope I'm missing something here; I'm setting up a UI with a bunch of custom events. Some of the events are really just aggregates of other events; for instance:
// ...
'cb-ui.hide': function(event){
// do stuff to hide
},
'cb-ui.close': function(event){
$(this).trigger('cb-ui.hide');
// more stuff for close
},
// ...
Given there is an animation in the cb-ui.hide event, like .fadeOut(1500), it appears (in my testing) that the remaining // more stuff for close doesn't wait for the animation to complete in the triggered event. I was thinking (previous to referencing the docs) that .trigger() would likely have an optional callback argument much like the animation methods:
$(this).trigger('cb-ui.hide', function(event){
// more stuff for close
});
But this doesn't appear to be the case. Since event triggers are not blocking (or don't appear to be at least), what can I do to force the desired functionality, while keeping with the event handler/trigger implementation that I've been building off of?
More specifically:
$('[data-cb-ui-class="window"]').live({
'cb-ui.hide': function(event){
$(this).find('[data-cb-ui-class="content"]').animate({
opacity: 0
}, 1000);
},
'cb-ui.show': function(event){
$(this).find('[data-cb-ui-class="content"]').animate({
opacity: 1
}, 1000);
}
'cb-ui.close': function(event){
$(this).trigger('cb-ui.hide');
$(this).find('[data-cb-ui-class="content"]').animate({
height: 'hide' // happening simultaneously to the animation of 'cb-ui.hide'
// expected to happen in tandem; one after the other
}, 1000);
},
'cb-ui.update': function(event, html){
// none of this is working as expected; the expected being, the 'cb-ui.hide'
// event is triggered (thus fading the [...-content] out) the HTML content is
// updated, then the [...-content] is faded back in from 'cb-ui.show'
// instead its just a mess that results in it fading out
$(this).trigger('cb-ui.hide');
$(this).find('[data-cb-ui-class="content"]').html(html);
$(this).trigger('cb-ui-show');
}
});
$('#foo').trigger('cb-ui.update', ['<p>Hello world!</p>']); // #foo is bound
This example animation should take ~2 seconds, but appears to be taking 1; both animations are occurring simultaneous to each other, rather than in logical order.
Not sure if I understand your question right, but does this make sense?
You can just pass another function to be run after the animation is done.
'cb-ui.hide': function(event, callback){
$('.lol').fadeTo(0,function() {
// fire callback
})
},
'cb-ui.close': function(event){
cb-ui.hide(e,function() {
// other stuff
});
},

What is the proper way in OpenLayers (OSM) to trigger a popup for a feature?

I have the feature ID, I can grab the marker layer on GeoRSS loadend, but I'm still not sure how to cause the popup to appear programmatically.
I'll create the popup on demand if that's necessary, but it seems as though I should be able to get the id of the marker as drawn on the map and call some event on that. I've tried using jQuery and calling the $(marker-id).click() event on the map elements, but that doesn't seem to be working. What am I missing?
Since I was asked for code, and since I presumed it to be boilerplate, here's where I am so far:
map = new OpenLayers.Map('myMap');
map.addLayer(new OpenLayers.Layer.OSM());
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));
//I've done some stuff as well in re: projections and centering and
//setting extents, but those really don't pertain to this question.
Elsewhere I've done a bit of jQuery templating and built me a nice list of all the points that are being shown on the map. I know how to do a callback from the layer loadend and get the layer object, I know how to retrieve my layer out of the map manually, I know how to iter over the layers collection and find my layer. So I can grab any of those details about the popup, but I still don't know how to go about using the built-in methods of the DOM or of this API to make it as easy as element.click() which is what I would prefer to do.
You don't have to click the feature to open a popup.
First you need a reference to the feature from the feature id. I would do that in the loadend event of the GeoRSS layer, using the markers property on the layer.
Assuming you have a reference to your feature, I would write a method which handles the automatic popup:
var popups = {}; // to be able to handle them later
function addPopup(feature) {
var text = getHtmlContent(feature); // handle the content in a separate function.
var popupId = evt.xy.x + "," + evt.xy.y;
var popup = popups[popupId];
if (!popup || !popup.map) {
popup = new OpenLayers.Popup.Anchored(
popupId,
feature.lonlat,
null,
" ",
null,
true,
function(evt) {
delete popups[this.id];
this.hide();
OpenLayers.Event.stop(evt);
}
);
popup.autoSize = true;
popup.useInlineStyles = false;
popups[popupId] = popup;
feature.layer.map.addPopup(popup, true);
}
popup.setContentHTML(popup.contentHTML + text);
popup.show();
}
fwiw I finally came back to this and did something entirely different, but his answer was a good one.
//I have a list of boxes that contain the information on the map (think google maps)
$('.paginatedItem').live('mouseenter', onFeatureSelected).live('mouseleave',onFeatureUnselected);
function onFeatureSelected(event) {
// I stuff the lookup attribute (I'm lazy) into a global
// a global, because there can be only one
hoveredItem = $(this).attr('lookup');
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
}
function onFeatureUnselected(event) {
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
/* Do something here to stop the indication of the onhover */
hoveredItem = null;
}
function findFeatureById(featureId) {
for (var key in map.layers) {
var layer = map.layers[key];
if (layer.hasOwnProperty('features')) {
for (var key1 in layer.features) {
var feature = layer.features[key1];
if (feature.hasOwnProperty('id') && feature.id == featureId) {
return feature;
}
}
}
}
return null;
}
also note that I keep map as a global so I don't have to reacquire it everytime I want to use it