How to bind Jquery dialog buttons to a knockout viewmodel

时间秒杀一切 提交于 2019-12-21 02:27:08

问题


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?


回答1:


  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/




回答2:


To add on to Andrew's answer, since the data-bind attribute is just another attribute you can add to your buttons, this would also work:

$("#dialog").dialog({
    buttons: [{
        text: 'Ok',
        'data-bind': 'visible: name().length'
    }]
});


来源:https://stackoverflow.com/questions/7801458/how-to-bind-jquery-dialog-buttons-to-a-knockout-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!