Popup using knockout js

2019-04-08 23:02发布

问题:

i'm migrating one of my older jquery plugins from DOM jungle to this fancy mvvm framework knockout.

Which technique would i use to properly display a popup container? I ahve to populate it 'by call' since i get a json feed every time.

I tried an approach using the with binding, but it still attempts to populate the partial at its first runtime.

<!-- ko with: daySubmitFormViewModel -->
    <div class="ec-consulation-lightbox">
        <form id="cForm" class="form-container">
           // Some bindings here.
        </form>
    </div>
<!-- /ko with: -->

回答1:

It can be done without custom binding as well. Example is below

            <div class="modalWindowBackground" data-bind="visible: popupDialog" >
                <div class="modalWindow" data-bind="with:popupDialog">
                    <div class="content">
                        <h2 data-bind="text: title"></h2>
                        <p>
                            <span data-bind="text: message"></span>
                        </p>
                        <div class="buttonSpace">
                            <input type="button" class="closeButton" data-bind="value: closeButtonText, click: $root.hidePopupDialog" />
                        </div>                            
                    </div>
                </div>
            </div>

Viewmodel code:

    self.showAlert = function (title, message, closeButtonText) {
        self.popupDialog({ title: title, message: message, closeButtonText: closeButtonText });
    };
    self.hidePopupDialog = function () {
        self.popupDialog(null);           
    };

  //Code which opens a popup
  self.remove = function () {
        .... some code ...
        if (someCondition) {
          self.showAlert('SomeTitle', 'Message', 'OK');
          return;
        }
        .... some code ...
   };


回答2:

Create a custom binding, have its open / close function trigger on a observable.

I've done a custom binding for jQuery Dialog that uses this approuch in combination with KO templates.

<div id="dialog" data-bind="dialog: { autoOpen: false, modal: true, title: dialogTitle }, template: { name: 'dialog-template', data: dialogItem, 'if': dialogItem }, openDialog: dialogItem"></div>

You can find my binding here along with some others https://github.com/AndersMalmgren/Knockout.Bindings

Live demo http://jsfiddle.net/H8xWY/102/



回答3:

https://github.com/One-com/knockout-popupTemplate

That pretty much does what you ask for. It's deeply configurable, and under steady development (we use it in our web applications ourselves).

Disclaimer: I'm a One.com developer. I am also the person who originated the above mentioned lib.