knockout.js中的事件绑定

event binding in knockout.js

本文关键字:事件 绑定 js knockout      更新时间:2023-09-26

我有一个带有answerGroup对象数组的viewModel。当其中一个answerGroup对象的反馈属性更新时,我想通过ajax将更新后的对象传递给我的ASP,从而将其保存到我的数据库中。Net MVC应用程序。

我不希望有一个典型的保存按钮或链接,而是希望在对象的属性更新后将对象传递给Ajax调用。我想我可以通过绑定到textarea元素的更改事件来实现这一点,但如果我这样做,就会调用ajax函数,但底层answerGroup对象的反馈属性不会更新。

我使用Knockout 1.2.1。下面是JavaScript代码,我还没有包含HTML。

我这样做是错误的,还是只是我对knockout.js事件绑定的语法不正确?

<script>
var viewModel = {}
$(function () {
    viewModel.scenarioId = ko.observable($("#Scenario_ScenarioID").val());
    viewModel.answerGroups = ko.observableArray([]);
    viewModel.addGroup = function (answerGroup) {
        // add item to beginning of array
        this.answerGroups.unshift(answerGroup);
    };
    ko.applyBindings(viewModel);
});
function answerGroup() {
    this.id = ko.observable();
    this.name = ko.observable();
    this.feedback = ko.observable();
    // the groups feedback has been updated so save
    // these details back to the server
    this.updateGroup = function (event) {
      // javascript api library that is an ajax function.
      // this works without a problem.
      api.updateAnswerGroup({
        success: function (result) {
            alert("saved!");
        },
        error: function (e) {
           alert("error!");
        },
        data: "answerswerGroupId=" + this.id + "&feedback=" + this.feedback
      });
      return true;
    };
}
</script>
<script id="answerswerGroupsTemplate" type="text/html">
  <div>
    <h4><a href='#'>${ $data.name }</h4>
    <div>
       <textarea cols="100" rows="2" data-bind="event: { text: feedback, change: updateGroup }">
       </textarea>                  
    </div>
  </div>
</script>

Knockout中处理此问题的典型方法是对您想要对其更改做出反应的可观察对象进行手动订阅。

所以,你可以做一些类似的事情:

function answerGroup() {
    this.id = ko.observable();
    this.name = ko.observable();
    this.feedback = ko.observable();
    this.feedback.subscribe(function (newValue) {
       //run your update code here
    }, this);
}

subscribe函数的第二个参数控制函数运行时的上下文("this")。

像这样的订阅的好处在于,当可观察对象以编程方式更改或基于UI中的绑定进行更改时,它将触发。

关于它的简要文档如下:http://knockoutjs.com/documentation/observables.html#explicitly-订阅可观测

我有一篇帖子,其中也包含了使用手动订阅的信息。

希望这能有所帮助。

我更喜欢订阅可观察的,就像RP Niemeyer描述的那样,但有时你需要附加到一个事件,而不是可观察的。因此,您可以使用"事件"绑定。文档中不包括"更改"事件,但我在v2.0.0rc版本中尝试过,它很有效:

<input data-bind="value: viewModel.MyProperty, event: { change: viewModel.MyPropertyChanged } />

http://knockoutjs.com/documentation/event-binding.html