3

The Code

I set up a jsFiddle at http://jsfiddle.net/6vd5C/1/

The JavaScript code in question:

var global_loggedOnUser = "User1";

$(function(){
  var viewmodel = (function(){
    this.feedbacktype = ko.observable("None");
    this.currentPage = ko.observable(location.href);
    this.currentUsername = global_loggedOnUser;

this.updateFeedbackType = function(item, event)
    {
      var newText = $(event.target).children("span").text();
      feedbacktype(newText);
    };

    return{
      pageUserIsOn : currentPage,
      theUser : currentUsername,
      feedbackType: feedbacktype
    };
  })();

  ko.applyBindings(viewmodel);
});

The Goal

Whenever someone clicks on the button of the submission, I'd like to see the "Current Type" bullet point update to indicate caption on the clicked button.

The Problem

  • Sometimes the text updates to the correct words; sometimes it updates but is a null value.
  • I cannot find a pattern or rhyme/reason; sometimes after being blank, clicking another element and then clicking the element that previously returned null now returned the correct text.

What am I doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
SeanKilleen
  • 8,809
  • 17
  • 80
  • 133
  • FYI, for others: After receiving Dimitar's answer below, I found this good answer elsewhere on SO describing the differences between target and currentTarget: http://stackoverflow.com/questions/5921413/difference-between-e-target-and-e-currenttarget – SeanKilleen Jul 28 '13 at 03:36

1 Answers1

6

Instead of using $(event.target) use $(event.currentTarget).

I'd like to expand a bit and explain the difference, when you use event.target you're getting the element that dispatched the event (the actual element literally) - like in your case, if you click on the <i></i> element which is nested within the button element, it will return the <i></i> notice that if you return the code to event.target and you click on the edge of your button it will work as expected.

In the case of event.currentTarget you're getting the element you're binding your listener to (which in your case is the actual button).

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79