Building SharePoint App Using JavaScript & REST with MVVM - TechNet Articles - United States (English) - TechNet Wiki

In this tutorial, we will be creating a simple SharePoint app which will Add a list item into a Customer List and then displaying all list items on the page.

Building SharePoint App Using JavaScript & REST with MVVM

  • Artifact: SharePoint App
  • Language : JavaScript, REST
  • Pattern: Model View ViewModel
  • Library: Knockout
  • Step 1: Create a Visual Studio Project using SharePoint App Template and select SharePoint hosted app

    Step 2: Add Knockout Java Script Library into your project

    Step 3:  Add new List 'CustomerList'

    Step 4: Create Namespace

    In JavaScript, namespacing at an enterprise level is critical as it's important to safeguard your code from breaking in the event of another script on the page using the same variable or method names as you are. Add the namespace in your app.js as follows:

    Step 5: Now let's work on the view model, first step will be creating the JavaScript library for binding, Create new JavaScript 'spdevstore.customer.js'

    Step 6: Modify spdevstore.customer.js and add following code

    "use strict";

    var spdevstore = window.spdevstore || {};

    spdevstore.customer = function (itm) {
    //private members
    var item = 'undefined',
    set_item = function (v) { item = v; },
    get_item = function () { return item; }

    //contructor
    item = itm;

    //public interface
    return {
    set_item: set_item,
    get_item: get_item,
    };

    Step 7: Create new javascript file 'spdevstore.viewmodel.js'

     

    Step 8: Modify spdevstoremodel.js

    "use strict";

    var spdevstore = window.spdevstore || {};

    spdevstore.viewmodel = function () {
    var customers = ko.observableArray(),

    get_customers = function () {
    return customers;
    },

    load = function () {
    // do something
    },

    create_Item = function (lname) {
    //do something
    };

    return {
    create_Item: create_Item,
    load: load,
    get_customers: get_customers,
    };
    }();

     Step 9: Add java script references in Default.aspx

    Step 10: Add a button to create Item and ul list to show results on default.aspx

    <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    <input type="button" value="Create Item" onclick="spdevstore.viewmodel.create_Item('Item Added');" />
    <div id="resultsDiv" style="overflow: auto"></div>
    <ul id="resultsTable" data-bind="foreach: get_customers()">
    <li>
    <span data-bind="text: get_item()" />
    </li>
    </ul>
    </asp:Content>

    Step 11: Now lets modify spdevstore.viewmodel.js to add REST for some CRUD operations

    "use strict";

    var spdevstore = window.spdevstore || {};

    spdevstore.viewmodel = function () {
    var customers = ko.observableArray(),

    get_customers = function () {
    return customers;
    },

    load = function () {
    $.ajax(
    {
    url: _spPageContextInfo.webServerRelativeUrl +
    "/_api/web/lists/getbyTitle('CustomerList')/items",
    type: "GET",
    he"resultsTable" data-bind="foreach: get_customers()">
    <li>
    <span data-bind="text: get_item()" />
    </li>
    </ul>
    </asp:Content>

    Step 11: Now lets modify spdevstore.viewmodel.js to add REST for some CRUD operations

    "use strict";

    var spdevstore = window.spdevstore || {};

    spdevstore.viewmodel = function () {
    var customers = ko.observableArray(),

    get_customers = function () {
    return customers;
    },

    load = function () {
    $.ajax(
    {
    url: _spPageContextInfo.webServerRelativeUrl +
    "/_api/web/lists/getbyTitle('CustomerList')/items",
    type: "GET", "accept": "application/json;odata=verbose",
    },
    success: function (data) {
    var results = data.d.results;
    //customers.removeall();
    for (var i = 0; i < results.length; i++) {
    customers.push(new spdevstore.customer(results[i].Title));
    }
    },
    error: function (err) {
    alert(JSON.stringify(err));
    }
    }
    );

    },

    create_Item = function (lname) {

    //Formulate the REST API URL to the Votes list
    var votesListURL = _spPageContextInfo.webServerRelativeUrl +
    "/_api/web/lists/getByTitle('CustomerList')/items";

    //Store the form digest
    var formDigest = $('#__REQUESTDIGEST').val();

    //send the REST request by using the jQuery ajax() function
    $.ajax({
    url: votesListURL,
    type: "POST",
    data: JSON.stringify({
    '__metadata': { 'type': 'SP.Data.CustomerListListItem' },
    'Title': lname
    }),
    headers: {
    'accept': 'application/json;odata=verbose',
    'content-type': 'application/json;odata=verbose',
    'X-RequestDigest': formDigest
    },
    success: function () {
    alert('Item Added!');
    location.reload();
    },
    error: function (err) {
    alert(JSON.stringify(err));
    }
    });

    };

    return {
    create_Item: create_Item,
    load: load,
    get_customers: get_customers,
    };
    }();

    Step 12: Modify app.js to bring everything together as following:

    'use strict';

    var spdevstore = window.spdevstore || {};

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

    // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
    $(document).ready(function () {
    getUserName();
    spdevstore.viewmodel.load();
    ko.applyBindings(spdevstore.viewmodel, $get("resultsTable"));
    });

    // This function prepares, loads, and then executes a SharePoint query to get the current users information
    function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
    }

    // This function is executed if the above call is successful
    // It replaces the contents of the 'message' element with the user name
    function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
    }

    // This function is executed if the above call fails
    function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
    }

    Step 13: That's it! Run your app by pressing F5.

     

      

     

    Reference - http://spdevstore.com/blogs/2013/08/28/building-sharepoint-app-javascript-rest-mvvm/