当我在Knockout.js中选择单选按钮的其他选项时,查找单选按钮的上一个值

时间:2012-05-15 15:04:57

标签: knockout.js

我在使用knockout js时遇到了问题。这里我使用的是可观察数组,其中属性名称selectedItem与radiobutton checked属性绑定。当我更改任何选项时,我想要点击之前的值和当前值。

<div style="font-size: 11px; line-height: 1.28; margin-left: 5px; margin-top: 10px;"
      data-bind="foreach:OptionDetail">
  <div>
    **<input  type="radio" class="mts" style="float: left; margin-left: 5px" data-bind="attr:{name:ParentCourseItemID,value:OptionDescription},click:function($root,event){SaveOptionForPoll($root,Option,SelectedItemID)},checked:SelectedItemID" />**
  </div>
  <input type="hidden" data-bind="attr:{id:'hdnSelectOption'+CourseItemID}" />
  <div data-bind="event: { mouseover: $root.ShowVoteCount, mouseout: $root.HideVoteCount }" style="margin-bottom: 5px; border: 1px solid #CCC; background-color: white;
                                zoom: 1; float: left; width: 210px; margin-left: 5px; height: 25px;">
    <div style="text-align: left; float: left; margin-top: 5px; margin-left: 5px;" data-bind="html:OptionDescription">
    </div>
    <div style="float: right; display:none; width: 50px; background-color: yellow; height: 52%; padding: 6px;"
        data-bind="attr:{id:'poll'+CourseItemID}">
      <span style="margin-right:5px;" data-bind="text:VoteCount"></span>Votes
    </div>
  </div>
  <div style="padding-left: 5px; padding-right: 5px; height: 100%">
    <span style="position: relative; top: 4px"></span>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

无法在每次当前值更改时记录上一个值。像。的东西。

var viewModel = function(data) {
    var self = this;
    this.value = ko.observable();
    this.previousValue = ko.observable(this.value());

    this.value.subscribe(function (newValue) {
        console.log("current value: " + newValue + " previousValue: " 
               + self.previousValue());
        // do something with previous value
        self.previousValue(self.value());    
    });
};

ko.applyBindings(new viewModel());

http://jsfiddle.net/madcapnmckay/2ZwDm/1/

希望这有帮助。