Friday, 27 January 2012

Working with CoffeeScript on SharePoint : ECMAScript Client Object Model

Now, the most interesting part of the series. We will be working with the ECMAScript Client Object Model through CoffeeScript.  The basic Create, Read, Update and Delete operations are done by using the ECOM with CoffeeScript:

Load the Client Object Model:
#Call the loadCOM function only if the sp.js script is loaded on this page.
ExecuteOrDelayUntilScriptLoaded loadCOM, "sp.js"
view raw exec.coffee hosted with ❤ by GitHub


Get the Title of the Current Web:
loadCOM = () ->
context = new SP.ClientContext.get_current()
web = context.get_web()
context.load web
context.executeQueryAsync ->
#Success Callback
alert web.get_title()
, (sender,args)->
#Failure CallBack
alert "Failed. #{args.get_message()} \n #{args.get_stackTrace()}"
view raw loadCOM.coffee hosted with ❤ by GitHub


Add Item to a List:
AddItem = () ->
context = new SP.ClientContext.get_current()
list = context.get_web().get_lists().getByTitle "CoffeeList"
listItemCreateInfo = new SP.ListItemCreationInformation
listItem = list.addItem listItemCreateInfo
listItem.set_item "Title","Mocha"
listItem.update();
context.executeQueryAsync ->
#Success Callback
alert "Item Added"
, (sender,args)->
#Failure CallBack
alert "Failed. #{args.get_message()} \n #{args.get_stackTrace()}"
view raw additem.coffee hosted with ❤ by GitHub


Update Item from List:
UpdateItem = () ->
context = new SP.ClientContext.get_current()
list = context.get_web().get_lists().getByTitle "CoffeeList"
listItem = list.getItemById 1
listItem.set_item "Title", "Latte"
listItem.update();
context.executeQueryAsync ->
#Success Callback
alert "Item Updated"
, (sender,args)->
#Failure CallBack
alert "Failed. #{args.get_message()} \n #{args.get_stackTrace()}"


Delete Item from List:
DeleteItem = () ->
context = new SP.ClientContext.get_current()
list = context.get_web().get_lists().getByTitle "CoffeeList"
listItem = list.getItemById 1
listItem.deleteObject();
context.executeQueryAsync ->
#Success Callback
alert "Item Deleted"
, (sender,args)->
#Failure CallBack
alert "Failed. #{args.get_message()} \n #{args.get_stackTrace()}"


Get All Items from List:
GetItems = () ->
context = new SP.ClientContext.get_current()
list = context.get_web().get_lists().getByTitle "CoffeeList"
listItems = list.getItems ''
context.load listItems
context.executeQueryAsync ->
#Success CallBack
itemEnum = listItems.getEnumerator()
alert itemEnum.get_current().get_item "Title" while itemEnum.moveNext()
,(sender,args)->
#Failure CallBack
alert "Failed. #{args.get_message()} \n #{args.get_stackTrace()}"
view raw getitems.coffee hosted with ❤ by GitHub
In this last piece of code, notice how the while loop in CoffeeScript makes it extremely easy to iterate over a ListItemCollection.

Next:Working with CoffeeScript on SharePoint : Interacting through jQuery
GitHub Link to the project: https://github.com/vman/SPCoffeeScript

No comments: