簡體   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