简体   繁体   中英

Multiple hashtag routes in backbone.js

I've got a project that requires a lot of user-input. It's basically a puzzle with six pieces, and the pieces are triggered by hashtag routes. Easy enough, right? I guess.

I have a great setup right now, where when a hash is reached("www.website.com/index.html/#test"), the first piece will appear. Now, this is great and all, but the thing is, the pieces can be triggered in any order, at any time. So if I had the following routes - "1", "2", "3", etc, it needs to be able to be something like: ("www.website.com/index.html/#3/#1/#2") or something similar. I can worry about making it look good at a later time, after I've figured out how to make it functional in the first place.

Here's the route code that I currently have -

<script>
    $(function(){

    var hideOne = function () {
        //alert("hideOne");
        var elem = document.getElementById("one");
        elem.className = "hide";
    };

    var Workspace = Backbone.Router.extend({
      routes: {
        "test":"test",// #test
      },    
      test: hideOne
    });

    var router = new Workspace();
    Backbone.history.start(); 

});
</script> 

So my question is; how do I make it so that I can have multiple hashtag routes in backbone.js?

Thanks in advance.

-Mitchyl

You could do something like this. Where you browse to stuff.com/path#hide/one/three here the routes with the (/:x) around them are dynamic matchers. so the () means it's optional and the :x means it will pass the string value from that part of the url fragment as an argument to the function called when the route is matched. So if your number of images is bounded to something pretty small this should be fine, I think.

<script>
  $(function(){
    var hideMany = function () {
      var toHide = [].slice.call(arguments);
      toHide.forEach(function (id) {
        if(id === null) { return }
        var elem = document.getElementById(id);
        if(elem) {
          elem.className = "hide";
        }
      });
    };

    var Workspace = Backbone.Router.extend({
      routes: {
        "hide(/:a)(/:b)(/:c)" : "test"
      },
      test: hideMany
    });

    var router = new Workspace();
    Backbone.history.start();

  });
</script>

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