2

エンティティ (私の例では Company) を更新または作成するためのフォームを含む Bootstrap Modal があります。現在、私の問題は、モーダルを使用してエンティティを表示すると、モーダルを閉じてもフィールドがクリアされないことです。「作成」ボタンをクリックすると、フォームが入力されたままになり、空白のモーダルが表示されます。

通常の JavaScript から ViewModels メソッドの 1 つを実行するにはどうすればよいですか? これが私のコードの一部です:

function ViewModel() {
        var self = this;

       function CompanyViewModel(company) {
            var self = this;
            self.Id = company.CompanyId;
            self.Name = company.Name;
        }

        function BlankCompanyViewModel() {
            var self = this;
            self.Id = 0;
            self.Name = "";
        }

        self.company = ko.observable();
        self.companies = ko.observableArray();


        self.clearCurrentCompany = function() {
            self.company(new BlankCompanyViewModel());
        };

       // Initialize the view-model
        $.getJSON("/api/company", function(companies) {
            $.each(companies, function(index, company) {
                self.companies.push(new CompanyViewModel(company));
            });
            self.clearCurrentCompany();
        });
    }

理想的には、次のようにモーダルの「非表示」イベントで ViewModel.clearCurrentCompany を実行したいと思います。

 $('#myModal').on('hidden', function() {
       //Do something here, not sure what
    });
4

2 に答える 2

4

モーダルの周りにカスタムバインディングを使用して、オブザーバブルの設定/クリアに基づいてモーダルを開いたり閉じたり表示したりするのが好きです。

何かのようなもの:

ko.bindingHandlers.modal = {
    init: function(element, valueAccessor, allBindings, vm, context) {
        var modal = valueAccessor();
        //init the modal and make sure that we clear the observable no matter how the modal is closed
        $(element).modal({ show: false, backdrop: 'static' }).on("hidden.bs.modal", function() {
            if (ko.isWriteableObservable(modal)) {
                modal(null);
            }
        });

        //apply the template binding to this element
        ko.applyBindingsToNode(element, { with: modal }, context);

        return { controlsDescendantBindings: true };
    },
    update: function(element, valueAccessor) {
        var data = ko.utils.unwrapObservable(valueAccessor());
        //show or hide the modal depending on whether the associated data is populated
        $(element).modal(data ? "show" : "hide");
    }
};

次に、これをオブザーバブルに対して使用します。オブザーバブルに対するバインディングのように機能withし、オブザーバブルが設定されているかどうかに基づいてモーダルを表示/非表示にします。

これが使用されていることを示し、モーダルが閉じられたときにカスタム コードを実行できるサブスクリプションを設定するサンプルを次に示します。 http://jsfiddle.net/rniemeyer/uf3DF/

于 2013-05-15T19:44:49.480 に答える