5

I am just sick of writing again and again the same piece of code to use jsom Async requests, especially when it's for a SP-hosted app which envokes spexecutor.

I am sure each developer has his own class-style code for this kind of job, but do you know if there is a library to go on with the boring stuff like this:

var clientContext = new SP.ClientContext(siteUrl);
var oWebsite = clientContext.get_web();
this.collList = oWebsite.get_lists();

clientContext.load(collList, 'Include(Title, Id)');
clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded), 
    Function.createDelegate(this, this.onQueryFailed)
);

4 Answers 4

7

Check out this blog post by Andrew Connell where he talks about using Breeze with SharePoint. With Breeze your code will look something more like:

var promise = breeze.EntityQuery 
  .from(contactType.defaultResourceName) 
  .using(entityManager) 
  .execute() 
  .where('Id', 'eq', 1) 
  .then(function (data) { return data.entity; }); 

// update the first item 
promise.then(function (contact) { 
    contact.Title = 'NewName'; 
    entityManager.saveChanges().then(function () { 
        jQuery("#results").html('saved first item in list'); 
    }); 
});

You may also find this presentation by Thorsten Hans interesting. He talks about a more comprehensive API abstraction for client-side SharePoint development.

1
  • 1
    Hi Rob, kinda honored to get your answer, big fan of your pluralSight tutorials! Breeze is not really our taste, so, we thought try our own project. We'll be very happy if you'd check this out. github.com/inedu/spyreqs More data in my response below, thanks!
    – JohnPan
    Commented May 2, 2014 at 12:28
5

When developing JavaScript apps against the SharePoint 2013 REST and CSOM APIs it is recommended to leverage Promises Patterns since it allows separate out the various asynchronous calls while still maintaining the dependency between them.

There are several techniques for implementing promises, but one of the easiest is to make use of the jQuery $.Deferred method.

Your example could be transformed into this one:

function getLists(properties){
    var dfd = $.Deferred();
    var ctx = new SP.ClientContext.get_current();
    var lists = ctx.get_web().get_lists();
    var includeExpr = 'Include(' + properties.join(',') + ')';
    ctx.load(lists, includeExpr);
    ctx.executeQueryAsync(
    function () {
       dfd.resolve(lists);
    }, 
    function (sender, args) {
       dfd.reject(args);
    });
    return dfd.promise();
}


//Usage
var properties = ['Title','Id'];
getLists(properties).then(function(lists){
       //...      
    },
    function(error){
      console.log(error.get_message()); 
    }
);

References

Using Promises Patterns in SharePoint 2013 Apps with JavaScript and jQuery

2
  • 1
    Unfortunately jQuery is not standards compliant. I would recommend to look at Q or RSVP instead, until promises become native (they are already in Chrome and Opera).
    – Christophe
    Commented Apr 30, 2014 at 20:59
  • Hi Vladim, I have got your method to work on a SP 2013 site but same code doesn't work on an 2010 mode site in my SP 2013 farm. I get the error "Unable to get property 'then' of undefined or null reference" Is this not supported on 2010 mode sites? PS: I have given reference to SP.js, sp.runtime.js, and jquery 2.1.4
    – Manu
    Commented May 29, 2015 at 14:29
2

My suggestion would be that you write your own module for your specific needs. Think about what would be needed to cover all methods (for example a CAML builder), a full library would be a monster. Rob's answer mentioning Breeze is probably the best you can get right now.

I have written my own library to abstract SOAP services, REST calls (listdata.svc, client.svc), rss calls, etc. The reason why I haven't done it for CSOM is that is has a dependency on the SharePoint js libraries that makes it difficult to port outside SP pages. Again, abstracting CSOM or the REST services is not easy and my solution is very basic.

You can find the version I wrote for SP 2010 here: http://sprest.codeplex.com/releases

2

Well, it's quite embarrassing to announce this way (-it was an admin's guideline) but we've already developed a proper js library for basic tasks with REST and JSOM. It's two guys two month's work, works with promises, needs jQuery, and we called it spyreqs. Not the best name choice, it stands for SharePointREQuestS. Two quick samples on usage, one with REST to query a list:

spyreqs.rest.getHostListItems(listTitle,query).then(function(data){
    var fields = data.d.results;
});

and one with JSOM to add a list item:

spyreqs.jsom.addHostListItem("My List", {"Title":"my item", "Score":90}).then(
    function(itemId) {
        alert("item was added, id:"+itemId);
    },
    function(error) {
        alert('addHostListItem request failed. ' +  error.args.get_message() + '\n' + error.args.get_stackTrace());
    }
);

It's that simple. You can use it for Host or Web lists/files. No need to setup anything, just include it. We made a real effort to write a nice documentation. Thw whole project is here: https://github.com/inedu/spyreqs The minified js file is 16Kb. It would be great if we could have some feedback. It worked for us, we never have to write stuff for the clientContext again, and we think it has already paid out the two months work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.