Здравствуйте, у меня есть шаблон нокаута JS для удаления и редактирования.
Это сценарий
<script id="RRitemTmpl" type="text/html">
<tr>
<td class="text-center" data-bind="text: Abbreviation"></td>
<td data-bind="text: lender"></td>
<td class="text-center" style="vertical-align:middle;">
<div data-bind="if: status() > 0">
<button type="button" class="btn btn-default btn-xs" data-bind="click: $parent.editItem">Edit</button>
<button type="button" class="btn btn-default btn-xs" data-bind="click: $parent.deleteItem">Delete</button>
</div>
<div data-bind="if: status() < 1">
<span data-bind="text: status_description"></span>
</div>
</td>
</tr>
</script>
<script id="RReditTmpl" type="text/html">
<tr>
<td class="text-center">
<select id="selected_currency_local" class="form-control input-sm" data-bind="options: $root.availableCurrencies,
optionsText: 'Abbreviation',
value: $parent.selectedCurrencyLocal,
optionsCaption: 'Choose...'">
</select>
</td>
<td class="text-center">
<input type="text" class="form-control input-sm text-left" data-bind="value: lender" />
</td>
<td class="text-center" style="vertical-align:middle;">
<button type="button" class="btn btn-default btn-xs" data-bind="click: $parent.acceptItemEdit">Accept</button>
<button type="button" class="btn btn-default btn-xs" data-bind="click: $parent.cancelItemEdit">Cancel</button>
</td>
</tr>
</script>
Вот модель, где шаблон должен открыться.
<!-- Bootstrap Modal dialog for allowing the user to edit his/her open loans data. -->
<div data-bind="bootstrapShowModal: modalThirdParty" class="modal fade">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!--
<div class="modal-header">
<button class="close" aria-hidden="true" type="button" data-bind="click: hideModalEditRiskRating">×</button>
<h4 class="modal-title"><?php /*echo lang("myprofile_pinfo_user_risk_rate"); */?></h4>
</div>
-->
<div class="modal-body" data-bind="with: userOpenLoan">
<form class="form-horizontal">
<div class="pull-left">
<h4 class="modal-title">3rd party risk raters.</h4>
</div>
<div class="pull-right">
<button type="button" class="btn btn-primary btn-sm" data-bind="click: $root.saveUserOpenLoanData">
<span class="glyphicon glyphicon-ok"></span> <?php echo lang("register_save"); ?>
</button>
<button class="btn btn-primary btn-sm" data-bind="click: $root.hideModalThirdParty">
<span class="glyphicon glyphicon-remove"></span> <?php echo lang("login_close"); ?>
</button>
<p/>
<p/>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped table-condensed">
<!-- <caption class="text-left"><p><strong><?php echo lang("myprofile_pinfo_user_risk_rate"); ?></strong></p></caption> -->
<thead>
<tr>
<th class="text-center tbl_col_width">Name</th>
<th class="text-center tbl_col_width">Value</th>
<th class="text-center tbl_col_width"><?php echo lang("myprofile_openloan_do_business"); ?></th>
</tr>
</thead>
<tbody data-bind="template: { name: templateToUse, foreach: items}"></tbody>
</table>
</div> <!-- table-responsive -->
<button type="button" class="btn btn-primary btn-sm" data-bind="click: addItem">New Item</button>
</form> <!-- Form Horizontal -->
</div> <!-- modal-body -->
<!--
<div class="modal-footer">
</div>
-->
</div>
</div>
</div>
Это файл нокаута JS, в котором я вызываю эту функцию, а также получаю данные из базы данных.
var ThirdPartyRRViewModel = function(parent, items) {
var root = parent;
var self = this;
this.items = ko.observableArray(items);
this.selectedItem = ko.observable();
/* Observable for storing the data of currency select. */
self.selectedCurrencyLocal = ko.observable();
this.addItem = function() {
var d = new Date();
var day = ("0" + d.getDate()).slice(-2);
var month = ("0" + (d.getMonth() + 1)).slice(-2);
var year = d.getFullYear();
var target_date = year + "-" + month + "-" + day;
$.each(root.availableCurrencies(), function (index, currencyItem) {
if (currencyItem.ID == root.userRiskRate().Currency) {
self.selectedCurrencyLocal(currencyItem);
}
});
var newLoan = {"ID":0, "ORIG_ID":0, "Currency":self.selectedCurrencyLocal().ID, "Abbreviation":self.selectedCurrencyLocal().Abbreviation,
"Amount":0, "date_borrowed":target_date, "monthly_amortization":0, "lender":"lender name",
"final_due_date":target_date, "status":1, "status_description":"Active"};
var newItem = new Item(newLoan);
self.items.push(newItem);
self.selectedItem(newItem);
};
this.deleteItem = function(itemToDelete) {
/* If ORIG_ID is greater than > 0, useropenloan row has been read from the database
and can not be removed, but cancelled. */
if (itemToDelete.ORIG_ID() > 0) {
itemToDelete.status(-1); /* Indicates to server that this item should be updated to cancelled. */
itemToDelete.status_description('Will be cancelled');
itemToDelete.itemIsEdited(1);
} else {
self.items.remove(itemToDelete);
}
self.selectedItem(null);
};
this.editItem = function(item) {
$.each(root.availableCurrencies(), function (index, currencyItem) {
if (currencyItem.ID == item.Currency()) {
self.selectedCurrencyLocal(currencyItem);
}
});
self.selectedItem(item);
};
this.acceptItemEdit = function() {
self.selectedItem().Currency(self.selectedCurrencyLocal().ID);
self.selectedItem().Abbreviation(self.selectedCurrencyLocal().Abbreviation);
self.selectedItem().Currency.commit();
self.selectedItem().Abbreviation.commit();
self.selectedItem().Amount.commit();
self.selectedItem().date_borrowed.commit();
self.selectedItem().monthly_amortization.commit();
self.selectedItem().lender.commit();
self.selectedItem().final_due_date.commit();
self.selectedItem().itemIsEdited(1);
self.selectedItem(null);
self.selectedCurrencyLocal(null);
};
this.cancelItemEdit = function() {
self.selectedItem().Currency.reset();
self.selectedItem().Abbreviation.reset();
self.selectedItem().Amount.reset();
self.selectedItem().date_borrowed.reset();
self.selectedItem().monthly_amortization.reset();
self.selectedItem().lender.reset();
self.selectedItem().final_due_date.reset();
self.selectedItem(null);
self.selectedCurrencyLocal(null);
};
this.templateToUse = function(item) {
return self.selectedItem() === item ? "RReditTmpl" : "RRitemTmpl";
};
};
/* Function for intializing the UserOpenLoansViewModel, that gets the
* open loans data by pushing retrieved open loans to self.userOpenLoan
* observable variable and by displaying that variable in a modal dialog. */
self.InitializeUserOpenLoansViewModel = function () {
$.ajax({
type: 'GET',
url: BASEURL + 'index.php/myprofile/getUserOpenLoan/' + auth,
contentType: 'application/json; charset=utf-8'
})
.done(function(openloanList) {
var loanItems = [];
$.each(openloanList, function (index, loan) {
var newLoan = new Item(loan);
loanItems[index] = newLoan;
});
self.userOpenLoan(new UserOpenLoanViewModel(self, loanItems));
})
.fail(function(jqXHR, textStatus, errorThrown) {
self.errorMessage(errorThrown);
alert( "Initializing the UserOpenLoansViewModel failed. Error code thrown: " + errorThrown);
})
.always(function(data){
});
};
При этом я вызываю шаблон и могу добавлять новые строки информации или удалять их, но не могу заставить их работать, когда нажимаю кнопку «Новый элемент».
Ваш селектор шаблонов является функцией, а не наблюдаемой
this.templateToUse = function(item) {
return self.selectedItem() === item ? "RReditTmpl" : "RRitemTmpl";
};
Так что вам нужно вызвать его, используя круглые скобки:
<tbody data-bind="template: { name: templateToUse(), foreach: items}"></tbody>
Других решений пока нет …