简体   繁体   中英

Call to application.js function in view .js file is not working?

I have the following function declared in application.js:

var cancelToggle = function(e, textToToggle, elementToToggle) {
  alert("hello");
  e.preventDefault();
  if ($(this).text() == "Cancel") {
    $(this).text(textToToggle);
  }
  else {
    $(this).text("Cancel");
  }
  elementToToggle.slideToggle();
}

For one of my models, I have an ajax response that attempts to bind the above function to a click event, here is the code in the .js.erb file:

$("#toggle_leave_team_<%= @team.id %>").on("click", cancelToggle(e, "Leave team", $("#confirm_leave_team_<%= @team.id %>")));

And the respective view code:

%p= link_to "Confirm Leave", idea_team_membership_path(@idea, @team, @team.membership_for(current_user)), :class => "btn", method: :delete, id: "confirm_leave_team_#{@team.id}", remote: true
= link_to "Cancel", "", class: "btn btn-large btn-block btn-primary", id: "toggle_leave_team_#{@team.id}"

My desired functionality is that by clicking the cancel button it shows/hides whatever selector is passed into the cancelToggle function while also changing the text of the button. Currently, when I press the cancel button, the page refreshes. I think the default is not being correctly prevented, but not sure how to solve this :(

You're invoking your function when you try to bind. The simplest solution would be to wrap it in an anonymous function. Added a .call to pass the this context through.

$("#toggle_leave_team_<%= @team.id %>").on("click", function(e) { cancelToggle.call(this, e, "Leave team", $("#confirm_leave_team_<%= @team.id %>")); }));

EDIT :

There's a cleaner way to do this using function currying

Modify your toggle function to be a function generator (it returns a function)

var createCancelToggle = function(textToToggle, elementToToggle) {
    return function(e) {
        e.preventDefault();
        if ($(this).text() == "Cancel") {
          $(this).text(textToToggle);
        }
        else {
          $(this).text("Cancel");
        }
        elementToToggle.slideToggle();  
    }
}

Now when you bind to the click event, you call createCancelToggle and pass the returned function to on() as the click handler:

$("#toggle_leave_team_<%= @team.id %>").on("click", createCancelToggle("Leave team", $("#confirm_leave_team_<%= @team.id %>")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM