Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Jquery dialog buttons to a knockout viewmodel

What I'd like to do is make a dialog where the buttons are databound to the knockout viewmodel so I can enable or disable those buttons depending on various conditions on the form

But the way you make buttons in jquery dialogs is a bit different than normal.

anyone have a solution for this?

like image 874
Keith Nicholas Avatar asked Oct 18 '11 01:10

Keith Nicholas


People also ask

Does Knockout use jQuery?

Any section of UI that should update dynamically (e.g., changing depending on the user's actions or when an external data source changes) with Knockout can be handled more simply and in a maintainable fashion. Knockout has no dependencies. It works without jQuery, Prototype.

What is $data in Knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is two way binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

What is Knockout ViewModel JS?

A ViewModel can be any type of JavaScript variable. In Example 1-3, let's start with a simple JavaScript structure that contains a single property called name .


1 Answers

  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/

like image 63
Andrew Whitaker Avatar answered Oct 02 '22 10:10

Andrew Whitaker