Knockout and Jquery Dialog

1,029 views
Skip to first unread message

Keith Nicholas

unread,
Oct 17, 2011, 7:56:06 PM10/17/11
to knock...@googlegroups.com
What I'd like to do is make a dialog where the buttons are databound so I can enable or disable those buttons depending on if the dialogs been filled out correctly by the user?

But, jquery dialog has a strange way of creating its buttons.....

anyone have a solution for this?

JayMangle

unread,
Oct 18, 2011, 12:16:10 AM10/18/11
to KnockoutJS
Hi Keith,

If you can create a jsfiddle demonstrating the problem it's easier to
help.

Thanks,
-Jason

rpn

unread,
Oct 18, 2011, 10:33:39 AM10/18/11
to knock...@googlegroups.com
Hi Keith-
I think that the easiest way to do this is to not use the dialog's buttons and instead create the buttons yourself.  If you make them jQuery UI buttons, then it will look identical.

Here is a sample: http://jsfiddle.net/rniemeyer/WpnTU/.  This uses custom bindings to initialize the dialog, the buttons, and to control toggling the dialog to be open/close.  You could certainly wire up the dialog and buttons outside of bindings, but I do think that the "openDialog" binding is helpful, so that your view model methods don't need to call .close() on the dialog.

You can then use the "disable" or "enable" bindings directly on the button elements.


Keith Nicholas

unread,
Oct 18, 2011, 3:35:03 PM10/18/11
to knock...@googlegroups.com
I asked on stackoverflow,  I got a good answer there..


  1. Make sure to apply your own class to the dialog's buttons:

    
    $("#dialog").dialog({
        buttons
    : [{
            text
    : 'Ok',
           
    class: 'ok-button'
       
    }]
    });
  2. Grab the button.ok-button and apply a data-bind attribute to it (visible here, just to show you that it works). Here, name is an observable property of our view model:

    
    $("button.ok-button").attr("data-bind", "visible: name().length");
  3. Apply bindings normally:

    
    var model = { name: ko.observable('') };
    ko
    .applyBindings(model);

Here's an example that hide's an "Ok" button on the dialog if name (an observable) has a length > 0:http://jsfiddle.net/9cRFy/

rpn

unread,
Oct 18, 2011, 3:43:06 PM10/18/11
to knock...@googlegroups.com
Nice.  I think that would work fine too.  

Personally, I prefer to keep my DOM specific code in bindings, so I think that the custom bindings would be my choice.  That way you can apply your bindings in markup to the buttons as normal.
Reply all
Reply to author
Forward
0 new messages