我正在尝试将click事件附加到每个循环内的模板中。我的模板看起来像这样。
<div class="col-md-6" data-bind="foreach: socialData">
<div class="col-md-12 horizontal-padding lib-item" data-category="view">
<div class="lib-panel">
<div class="row box-shadow">
<div class="col-md-4">
<!-- ko if: $data.hasOwnProperty("media_url") -->
<img class="lib-img-show" data-bind="attr: { src: media_url }">
<!-- /ko -->
</div>
<div class="col-md-8">
<div class="lib-row lib-header">
<span>
<span data-bind="text: full_name"></span>
(<span data-bind="text: user_name"></span>)
<!-- ko if: $data.hasOwnProperty("user_image") -->
<img class="pull-right img-circle thumbnail" data-bind="attr: { src: user_image }">
<!-- /ko -->
</span>
<div class="lib-header-seperator"></div>
</div>
<div class="lib-row lib-desc">
<span data-bind="text: text"></span>
<div class="lib-header-seperator"></div>
<hr/>
</div>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-warning feature"
data-bind="attr: { id: feature_id }">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>Feature
</button>
<button type="button" class="btn btn-danger"
data-bind="attr: { id: block_id }, click: blockItem">
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>Block
</button>
<!-- ko if: $data.hasOwnProperty("media_url") -->
<button type="button" class="btn btn-primary download"
data-bind="attr: { id: download_id }">
<span class="glyphicon glyphicon-download" aria-hidden="true"></span>Download
</button>
<!-- /ko -->
</div>
</div>
</div>
</div>
</div>
</div>
这是我的视图代码和ajax调用。
var targeturl = "/ajax/{{ event_id }}/";
var page = "0";
$(function () {
function fetch_data() {
$.getJSON(targeturl + page, function (data) {
// add block, feature and download ids
data1.forEach(function (item) {
item.block_id = "block-" + item._id;
item.feature_id = "feature-" + item._id;
item.download_id = "download-" + item._id;
});
var viewModel = {
socialData: ko.observableArray(data1),
blockItem: function(item) {
console.log(item);
}
};
ko.applyBindings(viewModel);
})
.error(function () {
alert('error');
});
}
// start function
fetch_data();
});
当我向click
淘汰赛添加data-bind
时,会发出错误:
ReferenceError:未定义blockItem
如何在数组项中附加click事件。
答案 0 :(得分:0)
问题是因为函数存在于比数组中当前绑定项更高的级别 - 它在每个单独的项上查找blockItem
。相反,您可以告诉它查看父上下文,以便它在您的viewmodel上找到它:
<button type="button" class="btn btn-danger"
data-bind="attr: { id: block_id }, click: $parent.blockItem">