0

I'm experiencing some strange behavior with .bind() and .unbind() in JQuery, even though my situation is seemingly identical to an example given on the JQuery site. In this case, the bind/unbind is applied to a JQuery tab (one of many). When the tab is clicked, it loads a controller action through ajax.

# show.html.erb:
$(document).ready( function(){
    var projectNav = function(){
        $("#tabs-project .loadingDiv").show();
        $.ajax({ url: "<%= url_for(params.except(:action).merge(:action => 'show_project')) %>", dataType: 'script' })
    };
    $("#projectMenuButton").bind('click', projectNav);
});

# show_project.js.erb
$("#tabs-project .loadingDiv").remove();
$("#tabs-project").append('<%= escape_javascript(render :partial => "profiles/project")%>')
$("#projectMenuButton").unbind('click', projectNav);

The .unbind() part isn't working like that - clicking the menu button again reloads the partial again.

When I change the existing unbind to $("#projectMenuButton").unbind('click');, it unbinds everything including the tab's principal function (to switch the view to the right div).

1 Answer 1

1

You have a scope problem... projectNav is only defined within the scope of the $(document).ready, so it is undefined when passed into unbind. A solution:

# show.html.erb:
var projectNav = function(){
        $("#tabs-project .loadingDiv").show();
        $.ajax({ url: "<%= url_for(params.except(:action).merge(:action => 'show_project')) %>", dataType: 'script' })
};
$(document).ready( function(){
    $("#projectMenuButton").bind('click', projectNav);
});

# show_project.js.erb
$("#tabs-project .loadingDiv").remove();
$("#tabs-project").append('<%= escape_javascript(render :partial => "profiles/project")%>')
$("#projectMenuButton").unbind('click', projectNav);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.