Bootstrap scrollspy and backbone routing

▼魔方 西西 提交于 2019-12-23 09:29:16

问题


How would i go about using Bootstrap's Scrollspy when I am using Backbone.js hash based routing?

Backbone router example, which creates page www.example.com/#somePage/123

var AppRouter = Backbone.Router.extend({
   routes: {
      "": "home",
      "somePage/:id": "somePage"
   },
   somePage: function (id) {
      console.log("do something");
   }
});

$(document).ready(function(){
   window.app = new AppRouter();
   Backbone.history.start();
});    

Twitter scrollSpy example which should append #anchor-value to the end the URL:

 <div id="navbar" class="row-fluid">
        <ul class="nav nav-pills navbar">
            <li class="active">
                <a href="#step1">1</a>
            </li>
            <li>
                <a href="#step2">2</a>
            </li>
      </ul>
    </div>
    <div data-spy="scroll" data-target=".navbar">
        <h4 id="step1">Step 1</h4>
        <p>Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.</p>
        <h4 id="step2">Step 2</h4>
        <p>Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.</p>
    </div>

This wants to turn the URL to something like www.example.com/#somePage/123#step1, which is not working.


回答1:


Here is a possible solution using the Bootstrap demo Scrollspy: https://jsfiddle.net/8wvdpddq/

Assuming you wish to have the URL updated and a history point added as the user scrolls, the following code should achieve it:

$('body').on('activate.bs.scrollspy', function () {
  var active = $('nav li:not(.dropdown).active a').attr('href').slice(1);
  window.app.navigate(active, {trigger: true});
  console.log('update url/history to ' + active);
})

In this case, trigger is also set, meaning your routing handlers will fire, if you don't want this, just remove this option.



来源:https://stackoverflow.com/questions/13695767/bootstrap-scrollspy-and-backbone-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!