2
votes

I have a ASP.Net MVC4 website that uses twitter bootstrap along with Knockoutjs. One of the requirements is to refresh the view model when the user toggles between some options. To do this, I have setup the following radio buttons

<div id = "myradio" class="btn-group" data-toggle="buttons-radio">
  <button value="1" type="button" class="btn btn-primary active" data-bind="click: refresh">1</button>
  <button value="2" type="button" class="btn btn-primary" data-bind="click: refresh">2</button>
  <button value="3" type="button" class="btn btn-primary" data-bind="click: refresh">3</button>
</div>​

My Knockoutjs view model is

function ViewModel() {
    var self = this;

    //this function is called when the radio button is clicked
    self.refresh = function(){
    alert($('#myradio > button.active').val());
    };
}

The problem I am having is that the click event is firing too soon and giving me the previous value of the radio button instead of current value. To demonstrate this problem, I have setup a jsfiddle

http://jsfiddle.net/73yMR/2/

Is there any way for me to get the current value? Does knockoutjs allow the event to be passed into the "refresh" function? I am open to any idea as long as I can detect which radio option is selected when the refresh function is run.

1

1 Answers

3
votes

Knockout passes the event object as the second argument (the first argument is the "current data") to the click handler function (you can read more about this in the documentation)

So the following code will produce the expected result:

self.refresh = function(data, element){
    alert($(element.currentTarget).val());
};

A working JSFiddle.