Backbone.js PushState True

前端 未结 2 712
天涯浪人
天涯浪人 2020-12-19 20:07

I\'ve created a site in backbone and for various reasons I\'ve decided I want to remove the hash in the URL. I\'ve changed history.start from



        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 20:20

    Now I see why the need to globally override the tag behavior isn't in the documentation. I think we are intended to use handle navigation in our views like so:

    MyView = Backbone.View.extend({
      events: {
        "click a.foo": "foo"
      },
    
      foo: function(e){
        e.preventDefault();
        history.navigate("foo");
        $("#output").append("foo");
      }
    });
    

    However if we want to retain the option to use simple HREFs in our tags we have to intercept the click behavior as in the above.

    If you have a hybrid app, some links internal to backbone, and some forcing a page refresh, it's not right to preventDefault() for every link. Links to other parts of the app will be broken.

    One can use a variation of the above and take advantage of the fact that if there is no internal view to navigate to, Backbone.history.navigate() will return false.

    $(document).on("click", "a", function(e)
    {
    
        var href = $(e.currentTarget).attr('href');
    
        var res = Backbone.history.navigate(href,true);
        //if we have an internal route don't call the server
        if(res)
            e.preventDefault();
    
    });
    

提交回复
热议问题