繁体   English   中英

knockout.js中的事件绑定

[英]event binding in 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>

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

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

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

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

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

希望这可以帮助。

我喜欢像RP Niemeyer描述的那样订阅observable,但有时你需要附加到一个事件而不是可观察的事件。 因此,您可以使用“事件”绑定。 该文档不包括“更改”事件,但我已经尝试使用版本v2.0.0rc并且它可以工作:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM