1

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 });
            });
        }
    };
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

1 Answers1

2

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.

jmacinnes
  • 1,589
  • 1
  • 11
  • 21
  • Makes sense. But if I have more then one button on the page I would have to add an item for every button to my view model. I guess I could do that but I would rather keep static ui display with the element but that is just me. I will try it out and see if I like it. – Mike Flynn Dec 09 '11 at 03:33