Friday, April 22, 2016

Get current Sharepoint list or document library via javascript object model

In server object model in Sharepoint there is simple way to get current list (i.e. list which is currently opened in browser window):

   1: var list = SPContext.Current.List;

In javascript object model it is not so obvious, but also possible. In order to get current list you have to use not very well known function GetCurrentCtx() defined in core.js. With this function we can get current list like this:

   1: var ctx = SP.ClientContext.get_current();
   3: var currentCtx = GetCurrentCtx();
   4: var list = ctx.get_web().get_lists().getByTitle(currentCtx.ListTitle);
   5: ctx.load(list);
   7: ctx.executeQueryAsync(
   8:     Function.createDelegate(this, function (sender, args) {
   9:         // use list here
  10:     }),
  11:     Function.createDelegate(this, function (sender, args) {
  12:         console.log("Error occured: " + args.get_message() }));

In this example the main difference between context created with SP.ClientContext.get_current() and context returned from GetCurrentCtx() is that last one has ListTitle property set to title of the current list or document library. Having it we can easily get list object from the web. Also this context contains other useful properties like listBaseType, listName, listTemplate and listUrlDir.

No comments:

Post a Comment