Furkan Bozdağ
Furkan Bozdağ

Reputation: 27

Knockoutjs Button Click

Hi how can ı get my value with knockoutjs click event my button code

 <button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"><span data-bind="text:LikeCount"></span> <i class="fa fa-thumbs-o-up"></i></button>

and my knockoutjs click code

 var LikeButtonClick = function () {
    alert("");
 }

And how can I refresh my likes after like button click event. I use template binding. My template binding code is

  var viewModel = {
            messages: ko.observableArray()
        };
        ko.options.useOnlyNativeEvents = true;
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });

and my like button code

var LikeButtonClick = function (id) {
            $.ajax({
                url: '/Home/Like/' + id,
                type: 'POST',
                success: function (data) {
                        // refresh
                        });
                }
            });
        }

Upvotes: 2

Views: 2027

Answers (2)

John Pavek
John Pavek

Reputation: 2665

Another method is to build the click function into your data model. Here I've added the function to the item directly. Each click will only affect it's own object information.

function Post() {
  var self = this;
  self.Text = ko.observable("Lorem Ipsum");
  self.Liked = ko.observable(false);
  self.LikeCount = ko.computed(function() {
    return self.Liked() ? 1 : 0;
  });
  self.MessageId = ko.observable(1);


  self.LikeButtonClick = function() {
    self.Liked(!self.Liked());
  }

}

function viewModel() {
  var self = this;

  self.Posts = ko.observableArray();

  self.Load = function() {
    self.Posts.push(new Post());
    self.Posts.push(new Post());
    self.Posts.push(new Post());
  }
  self.Load();
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="foreach: Posts">

  <div data-bind="text:Text"></div>
  <button data-bind="click: LikeButtonClick, value: MessageId" class="btn btn-default like">
<span data-bind="text:LikeCount"></span>
<i class="fa fa-thumbs-o-up"></i></button>
</div>

Upvotes: 2

BurnsBA
BurnsBA

Reputation: 4929

this context passed to the method will be your viewmodel, or whatever you have bound to the element. Inside LikeButtonClick you should be able to get the value of MessageId by referencing the property this.MessageId().

If you want to pass a value to the click handler, you'll want to declare an inline function where you data-bind, or alternatively, bind the function with a context. Here the context is the main viewmodel:

data-bind="click: LikeButtonClick.bind($root,'green')"

var LikeButtonClick = function (src) {
        alert(src); // src='green' in this example
    }

Upvotes: 1

Related Questions