Sunday, June 15, 2014

SharePoint Online (Office 365) Development - Part 3

1. Open App.js in editor. Add two new variables at the top:

 var context = SP.ClientContext.get_current();  
 var user = context.get_web().get_currentUser();  
 var web = context.get_web();  
 var lists = web.get_lists();  



Listing 13-3: Define variables

2. In the main function(), after getUserNames();, add following code:

 $("#getLists").click(function (event) {  
      showLists();  
      event.preventDefault();  
 });  

Listing 13-4: Call ShowLists()

3. Add following functions after the main function():

 function showLists()  
 {  
      lists = web.get_lists();  
      context.load(lists);  
      context.executeQueryAsync(onshowListsSuccess,onshowListsFail);  
 }  
 function onshowListsSuccess(sender, arg)  
 {  
      var lstEnum = lists.getEnumerator();  
      var strLists ='';  
      while(lstEnum.moveNext())  
      {  
           if (strLists==='')  
           strLists = lstEnum.get_current().get_title();  
           else  
           strLists += ', ' + lstEnum.get_current().get_title();  
      }       
      alert('Total # of lists is: ' + lists.get_count() + ' and List names are: ' + strLists);  
 }  
 function onshowListsFail(sender, args)  
 {  
      alert('Error occurred! Message: ' + args.get_message());  
 }  

Listing 13-5: Add functions

executeQueryAsync() executes the current pending request asynchronously on the server by using the client side object model (CSOM). It accepts two parameters. succeededCallback is a function or a delegate of the method to call if the request executes successfully. failedCallback is a function or a delegate of the method to call if the request fails to execute. When a function executes asynchronously, script continues to run without waiting for the server to respond.


lists.get_count() returns the count of lists in the site. lstEnum.get_current().get_title() where lstEnum is the list enumerator returns the title of each list. We store list titles in a string and then display the string when the list title reading loop has ended.

4. Click Run Project (play icon) button to run the app. App will run and display Get Lists button. Click it to see the result. An alert message will be displayed with the number of lists and their names.

Alert message showing list count and titles
This brings us to the end of the chapter. You have now acquired the knowledge to develop apps for the cloud. Modern apps use javascript heavily and it may be a good time to brush up your javascript programming skills. The focus of applications is moving from web to mobile and client side scripting provides the necessary boost that modern apps need, it keeps the pages light weight and thus apps can run easily in web as well as mobile environments.

No comments:

Post a Comment