0
我正試圖在準備好的文檔上預先清除一個淘汰組件。如何訪問Knockout組件中的viewModel?
我已經寫了下面的代碼:
function Finding(id, trigger) {
var self = this;
self.id = ko.observable(id);
self.trigger = ko.observable(trigger);
}
function FindingViewModel() {
let self = this;
self.findings = ko.observableArray();
self.addFinding = function() {
self.findings.push(new Finding(self.findings().length + 1, ""));
};
self.removeFinding = function (finding) {
self.findings.remove(finding);
ko.utils.arrayForEach(self.findings(), function (value, i) {
self.findings.replace(value, new Finding(i + 1, value.trigger()));
});
};
self.update = function (data) {
var findings = data.findings;
for (var index = 0; index < findings.length; ++index) {
var finding = findings[index];
self.findings.push(new Finding(self.findings().length + 1, finding.trigger));
}
};
}
ko.components.register('finding', {
template: `<table>
<tbody data-bind="foreach: findings">
<tr>
<td><span data-bind="text: id"/></td>
<td><input data-bind="value: trigger"/></td>
<td><a href="#" data-bind="click: $parent.removeFinding">Remove</a></td>
</tr></tbody></table>
<button data-bind="click: addFinding">Add a Finding</button>`,
viewModel: FindingViewModel
});
$(function() {
ko.applyBindings();
$.getJSON("/_get_findings", function (data) {
//findingModel.update(data);
})
});
我怎樣才能從發現組件從功能的getJSON設置裏面的數據訪問底層視圖模型?
什麼你所期望的,如果組件使用了網頁上多次發生的呢?乍一看,在視圖模型構造函數中調用'$ .getJSON'調用似乎更有意義,並且每個組件實例執行一次。 – Jeroen
這是一個好主意,我會嘗試! Thx –
太棒了!有效。非常感謝你! BRJörn –