Question

I am using knockout.js with jquery ui button. I built a custom binding on the button which is below. I am changing the text on the click item, but I also have additional click that submits an ajax request. What is the best design pattern to set the text back to the original text once the request is complete. I know I can do it manually or, pass the element being called to the method, but is there a more de-coupled way.

<button type="submit" data-bind="button: { text: 'login', pressed: 'authenticating...' }, click: function() { site.ajaxRequest(); }"></button>


ko.bindingHandlers.button = {
        init: function (element, valueAccessor) {

            var binding = ko.utils.unwrapObservable(valueAccessor());

            $(element).button({ label: binding.text }).click(function () {
                $(this).button({ label: binding.pressed });
            });
        }
    };
Was it helpful?

Solution

I wouldn't recommend binding the button to hardcoded text. Instead, I recommend binding the jQuery UI button to an observable and then updating that observable appropriately:

First snippet is a binding that can be used to update a jQuery UI button that I use. (psuedo code)

ko.bindingHandlers.buttonText =
{
    init: function (element, valueAccessor)
    {
        ko.bindingHandlers.buttonText.update(element, valueAccessor);
    },
    update: function (element, valueAccessor)
    {
        var binding = ko.utils.unwrapObservable(valueAccessor());
        $(element).button({label: binding});
    }
};

Next, here is what your binding would look like. This assumes you have an observable on your model called textObservable;

<button type="submit" data-bind="button: {buttonText: textObservable, click: site.ajaxRequest"></button>

Finally, in your ajaxRequest method, before you make the AJAX request, you need to update textObservable to 'Authenticating'. In the success handler of the ajax call, you need to update textObservable to your initial value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top