Select2 change ajax url

I'm working with knockout.js and select2 plugin.
I am trying to change select2 ajax url based on observable value.
for example if based on some choice I make an ajax call to 1 url or other. Here's some sample code:

<input type="hidden" data-bind="combobox: { optionsText: 'Name', optionsValue: 'ID', optionsCaption: '...', sourceUrl: partnerUrl }, value: ApplyToSubject" id="ApplyToSubject" name="ApplyToSubject">

      

This is how the sourceUrl: partnerUrl is retrieved:

self.partnerUrl = ko.computed(function () {
        var value = "";
        if (something)
        {
            value = apiUrls.customer;
        }
        else if (something else)
        {
            value = apiUrls.vendor;
        }
        else if(or another thing)
        {
            value = apiUrls.employee;
        }
        return value;
    });

      

I am working with custom binding. Here's the code for it:

// documentation http://ivaynberg.github.io/select2/
ko.bindingHandlers.combobox = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var optionsText = ko.utils.unwrapObservable(obj.optionsText);
        var optionsValue = ko.utils.unwrapObservable(obj.optionsValue);
        var sourceUrl = ko.utils.unwrapObservable(obj.sourceUrl);
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        var model = obj.model;
        var unwrapped = ko.utils.unwrapObservable(obj.model);

        $(element).select2({
            minimumInputLength: 3,
            formatResult: function formatResult(result) {
                return result.text;
            },
            data: function (model) {
                return { id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped }
            },
            initSelection: function (element, callback) {
                if (unwrapped && selectedID !== "") {
                    callback({ id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped });
                }
            },
            ajax: {
                quietMillis: 500,
                url: subdirUrl + sourceUrl,
                dataType: 'json',
                data: function (search, page) {
                    return {
                        page: page,
                        search: search
                    };
                },
                results: function (data) {
                    var result = [];
                    $.each(data.list, function (key, value) {
                        result.push({ id: value[optionsValue], text: value[optionsText], data: value });
                    });
                    var more = data.paging.currentPage < data.paging.pageCount;
                    return { results: result, more: more };
                }
            }
        });
        $(element).on('select2-selected', function (eventData) {
            if (eventData.choice) {
                // item selected
                var selectedItem = eventData.choice.data;
                var selectedId = eventData.choice.id;
                model(selectedItem);
            }
            else {
                model(undefined);
            }
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        $(element).val(selectedID).trigger('change');
    }
};

      

It works for a URL that doesn't change, but for URLs that need to be updated, I can't get it to work. (it looks like it saved the first url that was passed to (sourceUrl).

+3


source to share


1 answer


I finally managed to solve this problem.

From what I could read from the select2 documentation, you must pass a string or function to the ajax url parameter. So this is what I did - I wrote a function that returns the value of the observable (this is the url):

self.returnUrl = function () {
    return self.dynamicUrl();
};

      

And then I pass this function to my binding settings:



<input data-bind="combobox: { ... sourceUrl: $data.returnUrl }, value: ApplyToSubject" type="hidden" >

      

Then the custom binding works the same way as in the code in the question, with a slight change:

...
ajax: {
     url: sourceUrl <- this is the returnUrl function
...
}

      

+5


source







All Articles