开发者

JQuery .bind() / .unbind() problem

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( 开发者_如何学Cfunction(){
    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).


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜