繁体   English   中英

KnockoutJS / Bootstrap-使用javascript关闭模态时清除模态表单

[英]KnockoutJS/Bootstrap - Clearing modal form when closing modal using javascript

我有一个Bootstrap Modal,其中包含用于更新或创建实体的表单(在我的示例中为Company)。 现在,我的问题是,如果我使用模态查看实体,则无论如何关闭模态都不会清除字段。 如果我单击“创建”按钮,则仍要填充该表格,这将弹出空白模态。

如何仅从常规javascript执行我的ViewModels方法之一? 这是我的一些代码:

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
    });

我喜欢在模态周围使用自定义绑定,以基于填充/清除可观察对象来使其打开/关闭/显示。

就像是:

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/

function ViewModel() {
    var self = this;
    // your previous code
    $('#myModal').on('hide', function() {
       self.clearCurrentCompany();
    });
}

就这样 请注意,您要隐藏而不是隐藏,因为隐藏仅在模态完全消失后才会触发。 如果用户在上一个视图关闭之前打开了一个创建,它将仍然被填充。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM