[英]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.