knockout.js中的事件绑定

Rob*_*ini 19 javascript asp.net asp.net-mvc jquery knockout.js

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

我希望在更新对象的属性时将对象传递给Ajax调用,而不是使用典型的保存按钮或链接.我想我可以通过绑定到textarea元素的change事件来做到这一点,但如果我这样做,则会调用ajax函数,但不会更新底层的answerGroup对象的feedback属性.

我正在使用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: "answerGroupId=" + this.id + "&feedback=" + this.feedback
      });

      return true;
    };
}
</script>

<script id="answerGroupsTemplate" 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>
Run Code Online (Sandbox Code Playgroud)

RP *_*yer 42

在Knockout中处理此问题的典型方法是对observable进行手动订阅,以便对更改做出反应.

所以,你会做类似的事情:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

关于这样的订阅的好处是,当observable以编程方式更改或基于UI中的绑定进行更改时,它将触发.

关于它的简要文档:http://knockoutjs.com/documentation/observables.html#explicitly-subscribing-to-observables

我有一个职位,其中包括使用手动订阅的信息在这里了.

希望这可以帮助.