jQuery FullCalendar - create standard list of events from Gcal - javascript

I'm using FullCalendar in a project and the month view is great. But I also need to create a simple unordered list of the events gathered from 4 different Gcal feeds, and I haven't been able to do it. Anyone got any ideas? A quick response would be great.

Posting here the solution for adding a new view in fullcalendar.js. I needed to implement an Agenda or List view in fullcalendar.js for one of my projects. In this process, I got a chance to reverse engineer the code by Adam. I must say that this plugin uses some very good coding practices and javascript concepts.
I think that it would be useful for users if I share my findings and solution here. Included list view has following features:
Fully functional and customizable List/Agenda View
Pagination using the included arrow buttons
Click/Hover effects on the events
Dynamic calling of events for the list view using pagination
First of all, we CAN NOT do it without touching the fullcalendar sourcecode. Javascript does not allow that kind of extensibility. Howvever, I have kept things as simple as possible and I am also posting the steps to replicate it from scratch along with the sourcecode. This will be helpful in case of future updates of fullcalendar.js
First of all we need to define a new view for showing the list of events. Views are defined as objects in fullcalendar.js and can be added using constructor functions. You can find the construction function for list view on this URL https://gist.github.com/amitesh-m/5744528. This function defines and initializes a new view called "list". Inside it, renderEvents is the main member function that renders the available events on this view and attaches the click/hover event triggers.
Next we need to change the updateEvents function of Calendar object (around line# 500). This is done to unlink the default event calling behavior of fullcalendar.js for the list view. Modified function will look like this:
function updateEvents(forceRender) {
if (currentView.name == "list") {
currentView.visStart = new Date(0);
currentView.visEnd = new Date(currentView.page * 1000);
refetchEvents();
} else if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
refetchEvents();
}
else if (forceRender) {
rerenderEvents();
}
}
Everything will work as earlier for other views but now the calendar will send a slightly different request to the event server for the list view. Now, fullcalendar will set "start=0" and "end=1" when somebody clicks on the list view. Number of items to show on the page is to be managed by the server.
Next, we need to make a change in renderView() function of the calendar object (around line#374). This is to enable pagination on our list based on the arrow buttons which are alreaedy included in fullcalendar.js. This function should look like this:
function renderView(inc) {
if (elementVisible()) {
ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached
unselect();
if (suggestedViewHeight === undefined) {
calcSize();
}
var forceEventRender = false;
if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
// view must render an entire new date range (and refetch/render events)
currentView.render(date, inc || 0); // responsible for clearing events
setSize(true);
forceEventRender = true;
}
else if (currentView.sizeDirty) {
// view must resize (and rerender events)
currentView.clearEvents();
setSize();
forceEventRender = true;
}
else if (currentView.eventsDirty) {
currentView.clearEvents();
forceEventRender = true;
}
if (currentView.name == "list") {
forceEventRender = true;
if (inc == 1) {
currentView.page++;
currentView.title = "Page " + currentView.page;
} else if (inc == -1) {
currentView.page--;
currentView.title = "Page " + currentView.page;
}
}
currentView.sizeDirty = false;
currentView.eventsDirty = false;
updateEvents(forceEventRender);
elementOuterWidth = element.outerWidth();
header.updateTitle(currentView.title);
var today = new Date();
if (today >= currentView.start && today < currentView.end) {
header.disableButton('today');
} else {
header.enableButton('today');
}
ignoreWindowResize--;
currentView.trigger('viewDisplay', _element);
}
}
Now, when somebody clicks on previous or next buttons, the calendar will send a request for new event data to the server. Value of "start" will remain 0 throughout for the list view, while the value for "end" will represent the subsequent page numbers.
That's it. All you need to do now is call the list view in your full calendar options. This can be done by adding "list" to the "right" of header object as follows
header: {
left: 'prev,next today',
center: 'title',
right: 'list,month,agendaWeek,agendaDay'
}
The demo is available on this URL:
http://tas.co.in/fullcalendar-with-listview/

the clientEvents method will retrieve all the events fullCalendar has fetched & has in memory. not sure if this will help you all the way
http://arshaw.com/fullcalendar/docs/event_data/clientEvents/

Related

Possible to simulate select using setSelection?

I have a project where I am using the vis.js timeline module as a type of image carousel where I have a start and an end time, plot the events on the timeline, and cycle through them automatically and show the image attached to each event in another container.
I already have this working and use something similar to the following to accomplish this, except one part:
var container = document.getElementById('visualization');
var data = [1,2,3,4,5];
var timeline = new vis.Timeline(container, data);
timeline.on('select', function (properties) {
// do some cool stuff
}
var i = 0;
(function timelapseEvents(i) {
setTimeout(function(){
timeline.setSelection(data[i], {focus: true, animation:true});
if (i < data.length - 1) {
timelapseEvents(i+1);
}
}, 2000);
})(i)
The timeline.setSelection() part above works, the timeline event is selected and focused on. However, the "select" event is NOT triggered. This is verified as working as expected in the documentation (under Events > timeline.select) where it says: Not fired when the method timeline.setSelection() is executed.
So my question is, does anyone know how to use the timeline.setSelection() method and actually trigger the select event? Seems unintuitive to me to invoke the timeline.setSelection()method and not actually trigger the select event.
Spent a few hours on this and came up short. I ended up just taking the code I had in my timeline.on('select', function (properties) { block and turning it into a function and calling it after the timeline.setSelection() call.
Basically, I didn't fix the issue but worked around it. Will keep an eye on this in case anyone actually is able to figure out how to add the select() event to the setSelection() method.

ap-angular2-fullcalendar & external API

I´d like to add the ap-angular2-fullcalendar to my application. The birthdays from my users and other events should be displayed in the calendar. This is my template:
<angular2-fullcalendar *ngIf="isInitialized; else loadingTemplate"
#calendar
id="calendar"
(onDateChanged)="onDateChanged($event)"
[options]="calendarOptions">
</angular2-fullcalendar>
Then, I tried to add the events in the component like so:
ngOnInit() {
let e = this.memberService.members$;
e.subscribe((members: IMember[]) => {
this.loadBirthdays(members).then((events: ICalendarEvent[]) =>
this.setEvents(events));
});
}
loadBirthdays(members: IMember[]): Promise<ICalendarEvent[]> {
let years = [];
years.push(moment().subtract('1', 'year').format('YYYY'));
years.push(moment().format('YYYY'));
years.push(moment().add('1', 'year').format('YYYY'));
members.forEach((member: IMember) => {
if (member.mainData.birthday) {
for (let i in years) {
let event: ICalendarEvent = {
title: 'Birthday ' + member.firstName + ' ' + member.lastName,
start: moment(member.birthday).set('year', years[i]).format('YYYY-MM-DD')
};
this.events.push(event);
}
}
});
return Promise.resolve(this.events);
}
setEvents(events: ICalendarEvent[]) {
const cal = $('calendar');
if (events && events.length > 0) {
events.forEach(el => {
cal.fullCalendar('renderEvent', el);
});
cal.fullCalendar('rerenderEvents');
}
this.isInitialized = true;
}
When I now try to open the calendar, no events are displayed and no errors are show. when I do a console.log for the "el" in the foreach I get an object with the name and birthday in format YYYY-MM-DD
What is wrong with my code?
The issue you've got is quite simple - fullCalendar is not preserving your event when the view or date range is changed.
The renderEvent method (https://fullcalendar.io/docs/renderEvent) has a 3rd optional parameter "stick", which is false by default. The documentation states
Normally, the event will disappear once the calendar refetches its event sources (example: when prev/next is clicked). However, specifying stick as true will cause the event to be permanently fixed to the calendar.
So in other words, since your example event is in December, and presumably your calendar is initially displaying the current month (March at the time of writing this), when you try to navigate to December, every press of "next" causes the event source to be refreshed, and your manually inserted event is lot.
All you need to do is change your renderEvent line to this to set the "stick" option to true:
call.fullCalendar('renderEvent', el, true);
You also should not need cal.fullCalendar('rerenderEvents'); at all, this can be removed.
P.S. You may be able to make your code a little more efficient. For instance instead of looping through events, you could use "renderEvents" (https://fullcalendar.io/docs/renderEvents) to add them all to the calendar at once:
if (events && events.length > 0) {
cal.fullCalendar('renderEvents', events, true);
}
You may also want to consider whether you need to use renderEvent(s) at all - the more normal way to set events on your calendar is to use the events option in the calendar initialisation options. You can either set it as a static array of event objects (https://fullcalendar.io/docs/events-array), or a JSON or other custom feed from a URL (https://fullcalendar.io/docs/events-json-feed or https://fullcalendar.io/docs/events-function). The latter two also have the advantage that the calendar dynamically updates itself from the remote data source when navigating between views and dates.

Multiple fullacalendar widgets - synchronized view changes

I have a dashboard, where people can put multiple fullcalendar widgets (imagine a team dashboard with a fullcalendar widget for every person in a team). The main issue with this is performance. One client has 16 such widgets (all quite full of events) and they are not limited in number.
Only the first calendar has header controls (others have them hidden using CSS).
What I need is to propagate the changes to view (switch basicWeek to month etc.), firstDay (today in basicWeek, Monday everywhere else) and the date (prev, next, today) from first calendar to other calendars.
The issue is performance. As I didn't really find a way how to do it (that wouldn't look really hacky) except in viewRender, which is called for every single change. That means, if you switch from basicWeek to agendaWeek the first calendar propagates the firstDay to other calendars (which calls viewRender) and after that propagates the view change, which basically re-renders all calendars (except the first one) twice.
Is there a way to propagate those changes and manually call render on other calendars (from what I see in the source code, there might not be one), or a better way to do it?
I am also thinking about just destroying the calendars and re-initializing them with new options, but that might cause flashing (instead of quite a lot of lag caused by multiple re-renders). One of the options I thought of was using my own buttons (or re-using default buttons just unbinding original events from them), but even then I would still have to re-render the calendars multiple times in some occasions.
Switching view with 6 almost empty calendars takes about 3 seconds, which is unacceptable.
This is how my viewRender code looks like (this is inside own fullcalendar function, so every widget has its own scope with cached variables and settings)
viewRender: function(view) {
console.log('viewRender', calendarid, lastView, view.type);
// Propagate all changes from first calendar to other calendars on the page
if ($('#' + calendarid).parents('.widgetCalendar').is(':first-child')) {
// Change the first day (basicWeek is always today, other views are always Monday)
if (view.type != 'basicWeek' && currFirstDay != 1) {
currFirstDay = 1;
$('.calendarDiv').fullCalendar('option', 'firstDay', 1);
return;
} else if (view.type == 'basicWeek' && currFirstDay != firstday) {
currFirstDay = firstday;
$('.calendarDiv').fullCalendar('option', 'firstDay', firstday);
return;
}
// Propagate the view change to other calendars
if (lastView != view.type) {
lastView = view.type;
$('.calendarDiv:not(#' + calendarid + ')').fullCalendar('changeView', view.type); // , view.intervalStart.valueOf());
}
// Propagate the date change to other calendars
if (lastDate != view.intervalStart.valueOf()) {
lastDate = view.intervalStart.valueOf();
$('.calendarDiv:not(#' + calendarid + ')').fullCalendar('gotoDate', view.intervalStart.valueOf());
}
}
},
Ps.: At first I thought this issue is mainly ajax requests to get new events, but I changed that to a function which uses single call and caches the results. The main reason I thought that were some delays between ajax and that they weren't concurrent (session locking). But changing it to new function shows that the issue are indeed the re-renders which take white a long time per calendar (about 250 - 350ms).
If there is any info missing, ask in the comments and I will update the question.
Fullcalendar version: 3.4.0

Cannot reinitalize Sortable after ajax content update

I'm using Sortable to organise lists inside of parent groupings, which themselves are also sortable, similar to the multi example on their demo page, but with text. This works fine and uses code along the lines of:
var globObj = {};
function prepSortCats() {
globObj.subCatsGroup = [];
// Changing parent group order
globObj.sortyMainCats = Sortable.create(catscontainer, {
// options here omitted from example
onUpdate: function( /**Event*/ evt) {
// Send order to database. Works fine.
}
});
// Changing sub list order
globObj.subCatsGroup.forEach.call(document.getElementById('catscontainer').getElementsByClassName('subcatlist'), function(el) {
var sortySubCats = Sortable.create(el, {
// options here from example
onUpdate: function( /**Event*/ evt) {
// Send order to database. Works fine.
}
});
});
}
Which is called when the page loads using:
$(document).ready(function () {
// Sortable
prepSortCats();
});
All good so far. However, the user can introduce new elements into any of the lists (sub or parent). In brief, any new elements added by the user are first added to the database, then the relevant section of the page is refreshed using ajax to pull the updated content from the database and display that. The user sees their newly added items added to one of the existing lists. Ajax call is as follows:
function refreshCategories() {
var loadUrl = "page that pulls lists from database and formats it";
$("#catscontainer")
.html(ajax_load)
.load(loadUrl);
return false;
};
This works fine too. Except, Sortable no longer works. I can't drag any lists. My first thought was to destroy the existing Sortable instances and reinitialize them. Right after I called refreshCategories() I call the following:
if(globObj.sortyMainCats.length !== 0) {
globObj.sortyMainCats.destroy();
}
if(globObj.subCatsGroup.length !== 0) {
var i;
for (i = globObj.subCatsGroup.length - 1; i >= 0; i -= 1) {
globObj.subCatsGroup[i].destroy();
globObj.subCatsGroup.splice(i, 1);
}
}
prepSortCats();
But Sortable still has no effect. I introduced the global object (although controversial) so that I could target the Sortable instances outside their scope but I appear to have overlooked something. Any ideas? Apologies for not providing a working example. As I make various ajax calls to a server, I don't think this is possible here.
Update
I'm clearly misunderstanding some action that's taking place. Well, I should preface that by saying I missed that I could still organise the group/parent lists after reloading a section of the page by ajax with refreshCategories(). This is very much a secondary action to being able to sort the sub lists, which is what I noticed was broken and remains so.
But it did point out that although the entirety of $("#catscontainer") was being replaced with a refreshed version of the lists (and that's all it contains, list elements), Sortable still had some sort of instance running on it. I was under the understanding that it was somehow tied to the elements that were removed. Now I'm a bit more lost on how to get Sortable to either: (a) just start from scratch on the page, performing prepSortCats() as if it was a fresh page load and removing any previous Sortable instance, or (b) getting the remaining Sortable instance, after the ajax call to recognise the added elements.
Update 2
Making some progress.
Through trial and error I've found that right after calling refreshCategories(), calling globObj.sortyMainCats.destroy() is preventing even the group lists from being ordered. Then if I call prepSortCats() after this, I can move them again. But not the sub lists.
This isn't conclusive but it looks like I'm successfully destroying and reinitializing Sortable, which was my goal, but something about the ajax loaded elements isn't working with Sortable.
I was looking for the answer in the wrong place, being sure it was an issue with ajax loaded content and the dom having some inconsistencies with what Sortable expected.
Turns out it was an asynchronous problem. Or, to put it simpler, the section of the page being loaded by ajax wasn't quite ready when Sortable was being asked to be reinitalized.
For anyone having the same trouble, I changed:
$("#catscontainer")
.html(ajax_load)
.load(loadUrl);
to
$("#catscontainer")
.html(ajax_load)
.load(loadUrl, function() {
reinitSortable();
});
where reinitSortable() is just a function that fires off the destroy and prepSortCats() functions similar to how they're displayed above.

JavaScript architecture - mediators, when to use them?

This is more of a general question about the structure of my JavaScript code and if I'm going in the right direction towards well structured code.
The current code I've got:
(function (myNamespace, $, undefined) {
myNamespace.className = {
init:function { } // do stuff
}
} (window.myNamespace= window.myNamespace|| {}, jQuery)));
(function (myNamespace, $, undefined) {
myNamespace.className2 = {
init:function { } // do stuff
}
} (window.myNamespace= window.myNamespace|| {}, jQuery)));
Obviously with the above code, I can use the same Namespace (as per page/site section) and call them via myNamespace.className.init() etc. I can also combine these if I want to, but I'm encapsulating classes for readability.
Now, I've been reading http://addyosmani.com/largescalejavascript/ about the concept of mediators. My secondary question is when (and if) I should be using these? From className2 obviously I can do:
myNamespace.className2 = {
init:function { myNamespace.className.init() } // do stuff
}
So why would this ever subscribe to className like mediator.subscribe("classNameInit") and publish that event in className?
I'm highly open to suggestions about the structure of my code as this is something I need to get right whilst I'm changing the way I write my JavaScript.
You would use it when you have multiple pieces which will work together in unlimited combinations where you don't know all combinations ahead of time or where it's more efficient to assume all combinations.
Let's say you were building a social media app and you wrote a class to encapsulate a list of users. On some screens, clicking on a user in the list opens their profile, on another screen perhaps clicking a user searches for every comment they left, and on a third screen something else happens.
If you were to write this not using mediator/pubsub, what you'd end up with is a bunch of if statements in the onclick event...
UserList.prototype.onUserClick = function(user) {
// Check if we're supposed to open a popup
if (this.mode === 'profile')
// Check for something else
else if (this.mode === 'something else')
// Check for another case
else if (this.mode === 'foo')
}
Mediator is a solution to this problem because it doesn't require that UserList have knowledge of every single situation it might end up in. Instead, the above code in UserList could simply be refined to broadcast when a user is clicked on...
UserList.prototype.onUserClick = function(user) {
this.publish('user-click', user);
}
Then each of your other screens or UI pieces can simply listen for the user-click message...
// On pages where there needs to be a popup profile
Mediator.onMessage('user-click', function(data) {
showProfilePopup(data);
});
// Or perhaps on a search page
SearchBox.onMessage('user-click', function(data) {
this.searchByUser(data);
});
Furthermore, where mediator begins to shine is because these other UI components, like SearchBox are not interested in specifically when UserList fires a user-click, they're interested only when a user-click is published, other UI controls on the page can fire user-click as well and these pieces can react to it.
On a side note, className = { } isn't creating a class. What you probably want is className = function() { }.

Categories

Resources