Make your XPages more maintainable – JavaScript Callback functions

In this article I will attempt to explain the purpose and benefits of using callback functions in JavaScript.

Introduction

Basic JavaScript functions look like this normally like this

function addMe(a, b){
    return a+ b
}

JavaScript variables normally look like this

var a = 2
var b = 3

Finally we would call the function to add the variables

var theTotal = addMe(a, b)
//5

Seems simple enough

Setting a variable to a function

But we can also combine them into something like this

var totalThis = function(a, b){
    return a+b
}

var theTotal = totalThis(1, 2)
//3

The point of this simple demo is to illustrate that a variable can be “equal” to a function. So that means we can pass it around as a function.

Creating a callback function

Here is an example:

function addMe(a, b, callback){
    var theTotal = a+b
    callback(theTotal)
}

Which is called like this

var theTotal = addMe(1, 2, function(val){
    alert(val)
})

Which returns 3

Walking through that…

  1. We created theTotal variable and made it equal to a function call to addMe
  2. We called the addMe function passing 1, 2 and a function with a value as a parameter
  3. The addMe function received the variables and assigned the name of the incoming function – callback
    1. the incoming function now known as callback was passed a pointer “val” which means it can be called with a parameter later
    2. note there are no () after callback it is the function arguements
  4. The addMe function added theTotal of a+b
  5. the addMe function called the callback function passing a parameter of theTotal
  6. The resulting total was passed back to the addMe function and back to theTotal as 3

Making it optional

If you want to make the callback optional (so it does not have to be called) then all we need to do it test for its existence within the addMe function:

function addMe(a, b, callback){
    var theTotal = a+b
    if (callback){
        callback(theTotal)
    }
}

Some examples of why this makes your JavaScript code better

It is used in external libraries but other JavaScript developers and you will come across it and need to understand it. For example in jQuery, binding an event has been set up to allow “what you want to do after” to be passed in as a callback function. That gives maximum flexibility to the developer wanting to use bind().

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

The most common use would be in AJAX. Being asynchronous the webpage code carries on as if nothing else mattered once the ajax called is made. To get around this, modern JavaScript libraries use callback functions to process the data once the AJAX request is complete. So rather than having more code written after the AJAX call, the code is part of the function call which instantiates the AJAX in the first place. In this example the callback function is in the .done() part of the code which is itself a callback.

$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $(this).addClass("done");
});

And in XPages?

Well if you view the source of your XPage you will see a huge section at the end of the page with a whole load of functions and then a whole load of code which looks like XSP.attatchPartial (for example). That is dojo adding your programmatic events to the webpage onClientLoad as a callback.

For example here is a function

function view__id1__id11__id12__id113__id118_clientSide_onclick(thisEvent) {
    disableWorkingOverlay = true;
}

And here is the attachPartial which only names the function

XSP.attachPartial("view:_id1:_id11:_id12:_id113:_id118", "view:_id1:_id11:_id12:_id113:open",
        null, "onclick", view__id1__id11__id12__id113__id118_clientSide_onclick, 2,
        "view:_id1:_id11:_id12:_id113:myFilesPanel");

Generic Functions

What this really means is the ability to make more optimized (generic) code. If you have a process with 3 steps, you could hard code each step into 3 functions. Say for example

  • getData
  • processData
  • displayData

Well getData seem pretty generic to me and I expect we can use that more than once. So we would make a getData function, to which we would pass either the processData functionality (or) we would pass the necessary function call to take the data and move it to the next processData function. In that way we can use multiple dataSources and control the processing of the data from once central code block rather than having many individual code block for each individual process all over the place.

In the following code example the createGrid function is called as the callback function within the getGridData function. This makes the getGridData function completely generic and reusable. Get me some data and then do this with it.

var url = 'xRestService.xsp/byFirstNameFlat?count=100000', theData

var theCallBack = function(theData){
		createGrid(theData)
		}

getGridData(url, theCallBack)

//getGridData called from the code above
function getGridData(url, callback){

	$.ajax({
		  url: url
		}).done(function ( data ) {
			//one the data is loaded then pass it to the callback function
			//passed in as one of the function arguments
			if(callback){
				callback(data)
			}
		});
}

//createGrid - called from the callback function within getGridData
function createGrid(data){
	etc etc
}

Conclusion

You are going to see callback functions all over the place when you start to look into adding external libraries to your XPages. Don’t be afraid of them. Consider them when creating your XPages functionality – even if it is as an unused options within a function, you never know when you might be glad of that later in the application development.

Webcast: jQuery The World’s Most Popular JavaScript Library Comes to XPages – now on YouTube

It was an absolute pleasure to do my jQuery in XPages presentation for the 3rd time (publicly) earlier this week and it was as part of the TLCC and Teamstudio webcast series highlighting some of the people and presentations from the community.

There were 430 people registered for the webcast and at its peak there were over 300 people watching.

As with each presentation, podcast and screencast I have had the privilege of being a part of, I am humbled by knowing that I am able to help other developers and users in the community.

For those people who missed the presentation it was recorded and posted for posterity on youtube

Thank you to everyone who attended and let me know what you want to find out about in the future.

Marky

My first PSC star award – Advise

The company I am very proud to work for, PSC Group, has an excellent internal consultant personal growth program called the “5 points of excellence“.

This program allows consultants to grow and learn in 25 different areas from sales, to estimation, to development and others. PSC runs classes to promote individual areas of personal growth such as a consultant bootcamp, rainmaking seminars, personal image classes and many others. I have never worked for a company with such a focused and well defined career development path as this one and I believe it is good for the company and good for me on a personal level.

Earlier this week at the company’s quarterly meeting I was awarded my first star for “Advise”. Advise falls into the “Clients” category along with “Experience, Sell, Oversee and Relate”.

I am very proud to receive my first star after having worked at the company for only 9 months and I look forward to getting more in the near future.

IMG_20130417_205509_586

This star recognizes “becoming a trusted advisor to, and transcending an existing project, for a client” .

🙂

DCLUG April 24th – Getting Started with XPages

This month we are delighted to have Jeff Byrd from MAXIMUS come and speak to us about Getting Started in XPages. Jeff has over 15 years experience in Notes technologies and over 2 years of XPages experience to share.

http://www.dominotricks.com/?p=205

In this presentation Jeff will have a “nice and easy go at xPages covering design principals, basic CRUD and Views.  So if you’ve been meaning to check out XPages, but haven’t had the chance, please join us.”

Come and see for yourself, share your experiences and help to promote the DC user’s group 🙂

http://www.meetup.com/DC-Lotus-Professionals/events/112044682/

Location

IEG Briefing Center

600 14th Street, NW , Washington, DC

Agenda

————————————————————-

11:30am-12:00pm
Networking (lunch provided by IBM)
12:00pm-12:15pm
Welcome
Community Updates
Meeting date/schedule Questionnaire results/discussion
Agreement for next meeting date/time

12:15pm – 1:00pm – Presentation

Jeff Byrd: Getting Started with xPages

1:00pm-1:30pm
Questions/Answers Networking

1:30pm
END

Please mark the date in your calendar.

EXTJS in XPages #8 – Selecting data from the grid and opening a document

In this article I will show you how to get data upon selecting a document – I will then demonstrate how we open a document from the grid.

EXTJS in XPages series

Here are links to all of the previous articles in this series

Demonstration

The EXTJS in XPages demonstration database can be found at http://demo.xomino.com/xomino/Extjs.nsf/xGridOpenDocument.xsp

Download

The sample database that will accompany this series is  available from the menu in the live demo database from this link – http://demo.xomino.com/xomino/Extjs.nsf

Selection Model

The selection model for a grid is very easily retrieved using the dblclick event within the grid:

 var selection =  grid.getSelectionModel().getSelection();
 var fieldValue = selection[0].data.fieldname

Listeners

To detect the double click event we have to add a listener to the grid. There are many listeners for the grid and more information on them can be found here in the Sencha help files

grid = Ext.create('Ext.grid.Panel', {
	listeners: {      //listener config setting for the grid
		events HERE.....................
	}
}

Getting the UNID

In out view we are going to add a  new column docid – very simple @Text(@DocumentUniqueID) column formula. But this column is not going to be displayed in the view – it is going to be hidden.

We add the new column and add the “hidden: true” property to it in the grid so that it is not visible to the user. But this does mean that it is available to us programmatically.

{
	text: 'docid',
	width: 10,
	dataIndex: 'docid',
	hidden: true
},

(Note: the @UNID property is passed in by the REST service and *yes* we could use that instead of adding a new column – however I feel that this is easier to explain and does not require a discussion regarding the usage of a property of the REST service JSON array )

Opening the document

In our example grid we are simply going to open our document by getting the docid field from the hidden column and opening a window using a manually generated URL string

So all together or grid code now looks like this:

grid = Ext.create('Ext.grid.Panel', {
	renderTo: 'gridHere',
	frame: true,
	features: [filters],
	height: 400,
	title: 'Users',
	store: store,
	iconCls: 'icon-user',
	listeners: {      //listener config setting for the grid
		itemdblclick: function(dataview, record, item, index, e) {
			console.log('dblClick Event')
			var selection = grid.getSelectionModel().getSelection()
			window.open('xPerson.xsp?action=readDocument&documentId='+selection[0].data.docid)
		}
	}
}

As you can see from the example page this is simple, effective and completely poor as a user experience – but this article was about getting data from the grid – not about making a cool application 🙂

Conclusion

Programmatically accessing data in the grid is a very powerful technique when attempting to manipulate the EXTJS grids and insert them into your application.

Domino R9 – now FIPS 140-2 compliant – necessary for doing business with the DoD

As revealed in this years IBM Connect – ID109 IBM® Notes® and Domino® – Security Strategy – Domino R9 is now FIPS 140-2 compliant

About time too !!

The presentation can be downloaded from here

http://www.socialbizug.org/communities/service/html/communityview?communityUuid=0b366f56-cdf9-43d0-a5d3-4b2b96d86598#fullpageWidgetId=W3467cdf91608_40f1_b9fd_d0d2dcf37b05&file=b40036cc-ea99-4f44-9a60-6c3a93016816

From – http://en.wikipedia.org/wiki/FIPS_140
The 140 series of Federal Information Processing Standards (FIPS) are U.S. government computer security standards that specify requirements for cryptography modules. As of December 2006, the current version of the standard is FIPS 140-2, issued on 25 May 2001

FIPS-140 – what’s that then and who cares?

The bottom line is that the US government wants to be able to encrypt their networks and the FIPS compliance structure was created to ensure that all parts of the government could do business with the same encryption rules – still sounds like a good idea. The Notes/Domino architecture was years ahead of its time in realizing this corporate need !

I worked as a contractor to the DoD some years ago and they shut down their entire Notes R6.5 Intranet (13 years in the making) because it was not FIPS compliant. They moved to SharePoint (which for the record was not FIPS complaint but got “grandfathered in”….) and ended up with significantly less functionality. Some were happy about some were incensed, but it happened and the reason was justifiable (to them at least).

This means that FIPS compliance can no longer be a convenient excuse as to why Notes should be dropped in favor of another technology and it also brings it back to the table as a viable option for deployment in a  secure environment.

EXTJS in XPages #7 – Doing an @Unique(@DbColumn) equivalent in the grid

In this article I will show you how to make a simple @Unique(@DbColumn)) equivalent in the EXTJS grid

Introduction

When you have a notes view/EXTJS grid you often want to be able to do a lookup of all the unique values in a column – this is especially useful when you are also applying filters in the grid.

What is particularly useful is that the values in the column are uniqued automatically – this allows you to reduce down the values which are presented to the user to select from. This also means not having to create some elaborate search/filter capability going back to the server to change the lookup.

Caveat

This only works on the data in the current view so will not work if you are using remote filtering. In a later article I will demonstrate the new 4.2 BufferedRenderer which makes front end filtering on 10,000 documents a reality

The code

The code is very simple and can be demonstrated easily by adding a ComboBox to the grid – in this example the combobox is appended to the grid and the values come from the state field in the grid store

new Ext.form.ComboBox({
        renderTo: 'gridHere',
        store: grid.getStore().collect('state')
    });

ext1

Filtering the grid reduces the data

ext2

and then running the add combobox again now creates one with a reduced set – NOT the uniquing of the values automatically

ext3

To see the returned value we just use firebug and execute the collect method – you can see that the values are returned as an array – this could then be parsed into any field.

ext4

Conclusion

Using the EXTJS grid can be very much akin to using a notes view – the trick is having the knowledge to know what is possible.

PS

The data is returned in the order that it is presented in the grid – if you want alphabetically then so an array.sort()

🙂

Webinar – jQuery: The World’s Most Popular JavaScript Library Comes to XPages – April 23rd

I am very pleased to announce that as part of the TLCC 2013 XPages Webinar Series with Teamstudio I have been invited to give a webinar presentation of my IBM Connect 2013 presentation on jQuery. In this webinar I will be going through the slides and showing some demonstrations of how to use jQuery in XPages. There will also be a question and answer session at the end of the presentation for all those who are interested.

 

Tuesday,April 23rd – 10:30 A.M. to noon, Eastern U.S. time

Whether you want to add some serious eye candy to your XPages Applications or just want to do more with less code, jQuery, the world’s most popular JavaScript framework can help you. Come to this webinar and find out how you can use some of the thousands of jQuery plugins, in harmony with Dojo, within your XPages applications to create a better experience not only for your users, but for you as a developer. In this webinar, we’ll look at how jQuery works, how to add it to your XPages, and how a complete JavaScript beginner can take advantage of its power. We’ll demonstrate many working examples —  and a sample database will be provided.

 

For more information please look at the TLCC website link below and sign up

http://www.tlcc.com/admin/tlccsite.nsf/pages/xpages-webinar?opendocument