1

In my event handler function I need to check if some field is unique. To achieve this I use ajax call to the function in back end.

From that function data is send back using callback. at this moment I have Event handler:

self.searchKeyboardCmd = function (data, event) {
        if (event.keyCode == 13) { 

            foo(function (callback) {
              if(!callback){
                return false // Returning only from this method. Not parent method
               }
            });

            var a = new Eq();
            a.StorageId(self.StorageTemp());
            a.StartDate(self.StartDateTemp());
            a.DeviceSerialNumber(self.Test());
            a.DeviceId(self.DeviceTemp());
            a.Issue(self.Issue())
            a.IssueDesc(self.IssueDesc());
            a.Quantity(self.number());
            a.Project(self.Project());
            a.MeUser(self.MeUser());

            self.data.push(a);
            $('.datepicker').datepicker({ autoclose: true, todayHighlight: true/*, language: "pl"*/, format: 'dd/mm/yyyy' });
            self.Test("");
            return false;
        }
        return true;
    };

In which in lines:

foo(function (callback) {
    alert(callback);
});

I call this method with ajax call:

function foo(callback) {
    $.ajax({
        url: "/DeviceInstance/IsUnique",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        datatype: "json",
        data: JSON.stringify({ value: viewModel.Test() }),
        error: function (data) {
            alert("Dodanie  nie powiodło się " + data);
        },
        success: function (data) {
            callback(data);
        }
    });
}

At this moment correct data is received by foo in main method. But I need to make searchKeyboardCmd aware of the value of the callback value from Ajax call. I read in my other question that I need to make searchKeyboardCmd accepting callback from foo call.

Please do net send me to the question How do I return the response from an asynchronous call?. I'm reading that topic all day and still got nothing

Community
  • 1
  • 1
szpic
  • 4,346
  • 15
  • 54
  • 85
  • 1
    Seeing you are using jQuery you should be able to do this with the [**deferred object**](http://api.jquery.com/category/deferred-object/) using [**deferred.then()**](http://api.jquery.com/deferred.then/) which returns a [**Promise**](http://api.jquery.com/Types/#Promise). (The [**Promise**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) object will only be added in ES6 natively to JavaScript and is currently only supported in Chrome, Firefox and Opera) – Nope Jun 03 '14 at 11:59
  • Thanks. I will take a look at this. Unfortunately it must be working on IE10 so I can not use Promise mechanism – szpic Jun 03 '14 at 12:13
  • Deferred objects and promises in jQuery work just fine in IE10. It's a nice mechanism allowing you to nicely separate functional logic from UI rendering/display logic. I only mentioned ES6 as it will add Promise natively so you could also do it without jQuery then. – Nope Jun 03 '14 at 12:20

2 Answers2

1

What if you put all the code that depends on the callback return into the callback?

foo(function (callback) {
    if(callback) { // Changed this condition
        var a = new Eq();
        a.StorageId(self.StorageTemp());
        a.StartDate(self.StartDateTemp());
        a.DeviceSerialNumber(self.Test());
        a.DeviceId(self.DeviceTemp());
        a.Issue(self.Issue())
        a.IssueDesc(self.IssueDesc());
        a.Quantity(self.number());
        a.Project(self.Project());
        a.MeUser(self.MeUser());

        self.data.push(a);
        $('.datepicker').datepicker({ autoclose: true, todayHighlight: true/*, language: "pl"*/, format: 'dd/mm/yyyy' });
        self.Test("");
    }
});
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
1

Just an idea - this is jQuery way. This is your function:

function foo(callback) {
    return $.ajax({
        url: "/DeviceInstance/IsUnique",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        datatype: "json",
        data: JSON.stringify({ value: viewModel.Test() }),
        error: function (data) {
            alert("Dodanie  nie powiodło się " + data);
        },
        success: function (data) {
            callback(data);
        }
    });
}

$.ajax - returned a Defered object.

This is modified searchKeyboardCmd function:

self.searchKeyboardCmd = function (data, event) {
    var dfd = $.Deferred();

    if (event.keyCode == 13) {

        foo(callback).done(
            function() {
                var a = new Eq();
                a.StorageId(self.StorageTemp());
                a.StartDate(self.StartDateTemp());
                a.DeviceSerialNumber(self.Test());
                a.DeviceId(self.DeviceTemp());
                a.Issue(self.Issue())
                a.IssueDesc(self.IssueDesc());
                a.Quantity(self.number());
                a.Project(self.Project());
                a.MeUser(self.MeUser());

                self.data.push(a);
                $('.datepicker').datepicker({ autoclose: true, todayHighlight: true/*, language: "pl"*/, format: 'dd/mm/yyyy' });
                self.Test("");
                dfd.resolve();
            }
        );
    }

    dfd.reject();
};

This code is untested. When you write JavaScript you must thing asynchronously. If you provide working jsFiddle with your solution I can help you more.

Best regards.

Georgi Naumov
  • 4,160
  • 4
  • 40
  • 62