有模板:
<table data-bind="foreach: {data: messages, as: 'message'}">
<tr> <td data-bind="text: $root.go"></td> </tr>
</table>
我的js:
function CreateViewModel() {
var self = this;
this.go = ko.computed(function() {
return 'not really important what here for now';
});
}
ko.applyBindings( new MessagesVM );
运行时“go”中的上下文是“window”,我希望它是当前项目。
是否可以?
如果我将 tmpl 行更改为“<td data-bind="text: go"></td>
”,则会出现错误 ['go' 未定义]。
最佳答案
The context in 'go' while runtime is 'window', I want it to be the current item. Is it possible?
我认为你不能通过计算,不。如果你使它成为一个简单的函数,你可以: data-bind="text: $root.go.call(message)"
(一般来说它是 .call($data)
,但由于您在 foreach
中命名它):
function MessagesVM() {
var self = this;
this.messages = ko.observableArray([
"Message 1",
"Message 2"
]);
this.go = function() {
return 'this is: "' + this + '"';
};
}
ko.applyBindings(new MessagesVM);
<table data-bind="foreach: {data: messages, as: 'message'}">
<tr>
<td data-bind="text: $root.go.call(message)"></td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
或者,如果您想要计算但作用于单个项目的某些功能,我可能会使用绑定(bind)处理程序:
ko.bindingHandlers.specialText = {
update: function(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.innerHTML = "'value' is " + value;
}
};
function MessagesVM() {
var self = this;
this.messages = ko.observableArray([
"Message 1",
"Message 2"
]);
}
ko.applyBindings(new MessagesVM);
<table data-bind="foreach: {data: messages, as: 'message'}">
<tr>
<td data-bind="specialText: message"></td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
关于javascript - knockout js foreach循环上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587127/