淘汰js foreach循环上下文

时间:2016-02-23 20:05:36

标签: javascript knockout.js

有模板:

<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 );

&#39; go&#39;运行时是&#39; window&#39;,我希望它是当前项目。 可能吗? 如果我将tmpl行更改为&#34; <td data-bind="text: go"></td>&#34;我会有一个错误[&#39;去&#39;没有定义]。

2 个答案:

答案 0 :(得分:1)

  

&#39; go&#39;运行时是&#39; window&#39;,我希望它是当前项目。有可能吗?

我认为你不能用计算机,没有。如果你使它成为一个简单的函数,你可以:data-bind="text: $root.go.call(message)"(通常它是.call($data),但是因为你在foreach中命名它:

&#13;
&#13;
function MessagesVM() {
  var self = this;
  this.messages = ko.observableArray([
    "Message 1",
    "Message 2"
  ]);
  this.go = function() {
    return 'this is: "' + this + '"';
  };
}

ko.applyBindings(new MessagesVM);
&#13;
<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>
&#13;
&#13;
&#13;

或者,如果你想要计算某些功能但是对单个项目起作用,我可能会使用绑定处理程序:

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将其转换为函数并传递上下文。作为计算,它具有缓存值,因此不能与上下文相关。

&#13;
&#13;
function CreateViewModel() {
  var self = this;
  this.messages = [
    'one',
    'two'
  ];
  this.go = function(data) {
    var context = data;
    return 'Context:' + context;
  };
}

ko.applyBindings(new CreateViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table data-bind="foreach: {data: messages, as: 'message'}">
  <tr>
    <td data-bind="text: $root.go(message)"></td>
  </tr>
</table>
&#13;
&#13;
&#13;