dcsimg
 

Patterns and Practices JavaScript Core Library for Office 365

Wednesday Jun 29th 2016 by Sandeep Chanda
Article Image

Learn more about the release of a JavaScript Core Library that packages some of the common practices to accelerate the development of SharePoint using client-side technologies.

With most of the SharePoint development now focusing around leveraging the Client Side Object Model (CSOM), guidance was long due from the community to write down the best practices to leverage the model using JavaScript. The Office 365 developer patterns and practices team has recently announced the release of a JavaScript Core Library to package some of the common practices and accelerate the development of SharePoint using client-side technologies.

The library provides fluent APIs to perform CSOM operations. In addition, it also has support for ES6 promise specifications for chaining asynchronous operations. The library works perfectly with in a SharePoint script editor Web part as well as with a module loader like requirejs.

To configure, first you can add the NodeJS package to your project using NPM:

npm install sp-pnp-js --save-dev

Once you have configured the package, you can import the root object and start interaction with the API. You can also leverage the API from within a Visual Studio TypeScript project. First you need to add the requirejs NuGet package and then use the module loader to load the pnp library.

Here is the requirejs code illustrating the module dependencies:

require(["jquery", "pnp", "fetch", "es6-promise.min"], function ($, app) {

    $(function () {
        app.render($("#content"), {
            "jquery": $
        });
    });

});

You will notice that apart from the module dependencies for jquery and the app launcher, there is additional dependencies for fetch and es6 promise modules. The fetch library supports cross origin request response against an API. The es6 promise library allows you to chain requests based on the promise style of programming in JS.

Here is a sample app code leveraging the pnp module:

import pnp from "pnp";

class App {

    render(element: HTMLElement, preloadedModules: any[]) {

        let $ = preloadedModules["jquery"];

        $(element).append(`${pnp.sp.web.select("Title").get()}`);
    }
}

You can also leverage the promise style as shown in the example below:

pnp.sp.crossDomainWeb().select("Title").get().then(function (result) {
         //perform further operations on result
    });
Home
Mobile Site | Full Site