Saturday, August 20, 2016

Knockout observable array options binding issue with AJAX loading

I had an issue where when I loaded all the element using jQuery AJAX synchronous option the binding worked perfectly but it didn't work when I loaded the array using asynchronously. Here is my finding in case if any one else come up with the same issue.

    function ViewModel()
    {
        var self = this;
        self.AllSubjects = ko.observableArray();
        $.ajax({
            url: all_subject_url,
            type: 'post',
            data: '',
            async: false,
            success: function (result) {
                var response = JSON.parse(result);
                if (response.status == 'success')
                {
                    var mapped = ko.mapping.fromJS(response);
                    if (mapped.Subjects()) {
                        self.AllSubjects = mapped.Subjects;
                    }
                }
            }
        });

        <select class="form-control" name="subject" data-bind="options:$root.AllSubjects,optionsText:'name',optionsCaption:'Select Subject',optionsValue:'id',value:subject">
        </select>

The above code work fine when loading values synchronusly, but won't work if you remove the async=false option in the $.ajax option. The issue with one the AJAX data is loaded we are replacing the AllSubjects observable array with new observable array. The correct way to map it as below.

self.AllSubjects(mapped.Subjects());

No comments:

Post a Comment