是否可以将Knockout.JS变量传递给onclick函数而不进行绑定?

时间:2017-07-11 22:39:26

标签: javascript knockout.js

是否可以将Knockout.JS变量传递给onclick函数而不将该函数绑定到视图模型?

下面,我尝试传递以下特定行的用户名参数:

<tbody data-bind="foreach: viewModel">
        <tr>
            <td data-bind="text: UserId"></td>
            <td><button onclick="alertRowName($element.UserName)"></button></td>
        </tr>
</tbody>

<script>
  function alertRowName(string){
    alert(string);
  }

//in my example the model is from a c# viewmodel..
viewModel = ko.mapping.fromJS(model);
var jsModel = ko.toJS(viewModel);    
ko.applyBindings(viewModel);

</script>

1 个答案:

答案 0 :(得分:2)

你可以这样做。
修改

嗯......刚刚注意到没有绑定。你能否解释为什么没有约束力?

&#13;
&#13;
var app = Window.app || {};
app.model = [{
  UserId: 1,
  UserName: "User Name Here",
}];

app.ViewModel = function ViewModel(model){
  var self = this;
  self.data = ko.mapping.fromJS(model);
};

app.ViewModel.prototype.alertRowName = function alertRowName(user) {
  alert(user.UserName());
};

ko.applyBindings(new app.ViewModel(app.model));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>

<table>
  <tbody data-bind="foreach: data">
    <tr>
      <td data-bind="text: UserId"></td>
      <td><button data-bind="click: $root.alertRowName, text: UserName"></button> </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

当心......这里是龙

您可以执行以下操作,但我强烈建议您不要这样做。 这是将一个函数附加到Window对象,使其成为一个全局函数。每个事件处理程序通常都有一个可以使用的事件对象。

&#13;
&#13;
var app = Window.app || {};
app.model = [{
  UserId: 1,
  UserName: "User Name Here",
}];

app.ViewModel = function ViewModel(model){
  var self = this;
  self.data = ko.mapping.fromJS(model);
};

app.ViewModel.prototype.alertRowName = function alertRowName(user) {
  alert(user.UserName());
};

ko.applyBindings(new app.ViewModel(app.model));

Window.myButtonClick = function(){
  var item = ko.dataFor(event.currentTarget);
  alert(item.UserName());
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>

<table>
  <tbody data-bind="foreach: data">
    <tr>
      <td data-bind="text: UserId"></td>
      <td><button onclick="Window.myButtonClick()" data-bind="text: UserName"></button> </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;