Sunday 19 February 2012

Passing argument to async callback function: Sharepoint 2010 ECMA Script

Hi
Below is the example which shows how to pass the argument to the async call back function through the ECMA script in SharePoint 2010. There might be need for developer to know for which call I am getting the success message and do some event logging or something. Below example shows how that can be achieved.


<script language="ecmascript" type="text/ecmascript">

        var fieldCollection;
        var field;
        var list;
        function getFieldType() {
            var clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("PeopleList");
                this.fieldCollection = list.get_fields();
                this.field = fieldCollection.getByTitle("Title");

                clientContext.load(this.field);

var myCallBack = Function.createCallback(OnLoadSuccess, this.field);
                clientContext.executeQueryAsync( Function.createDelegate(this, myCallBack), Function.createDelegate(this, this.OnLoadFailed));
alert('In main function... ' + field.get_title());
            }
        }
        function OnLoadSuccess(sender, args, field1) {
            alert('In callback success... ' + field1.get_title());

        }
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script><input id="btnGetFieldType" onclick="getFieldType()" type="button" value="Get Field Type"/>  

4 comments:

  1. Thank you Kiran. This solution is really helpful.

    ReplyDelete
  2. This works fine for a single call. If multiple calls are being made, the last value in the parameter will be passed to the callback. I have a loop that performs the async call and all success methods receive the exact same value. (The last value)

    ReplyDelete
  3. thanks for your idea its helping my project

    ReplyDelete