Problem to link buttons with backbone.js

1

I just started using the backbone.js framework using router to generate urls in my html. I have 3 buttons defined so

        <ul class="list-inline ">
            <li><button id="boton1" type="button" class="btn btn-primary" href="#vistade1">1</button></li>
            <li><button id="boton2" type="button" class="btn btn-primary" href="#vistade2">2</button></li>
            <li><button id="boton3" type="button" class="btn btn-primary" href="#vistade3">3</button></li>
        </ul>

and my backbone code is this

(function(){
var Router = Backbone.Router.extend({
  routes: {

        "boton1/:id" : "vistauno",
        "boton2/:id" : "vistados",
        "boton3/:id" : "vistatres"
},

  vistauno: function (boton1) {
      console.log("estas intentando acceder a "+boton1);
},
  vistados: function (boton2) {
      console.log("estas intentando acceder a "+boton2);
},
  vistatres: function (boton3) {
      console.log("estas intentando acceder a "+boton3);
}

});
var Router = new Router(); 
    Backbone.history.start();
});

It works for me when I put the path index.html#boton2 or index.html#boton3 by hand but if I give it by pressing the button it does not work.

    
asked by Cucumberita 22.06.2016 в 15:37
source

2 answers

2

Backbone routes control what you do when you change the URL in the browser, just like you do when you type it "by hand".

Neither button nor li change the URL in the browser by themselves, that's what the a tags do, or with JavaScript events (as @Miquel mentions).

Try with:

<li><a id="boton1" type="button" class="btn btn-primary" href="#boton1/1">1</a></li>

If you also want it to look like a button you will only have to change its appearance with CSS.

Notice, incidentally, in the "href", I've set it according to the format you give in the Backbone routes; href="#vistade1" is not a route that you have controlled, according to the code you have pasted.

    
answered by 23.06.2016 / 13:27
source
1

You need to define the events :

events: {
    "click #boton1": "vistauno",
    "click #boton2": "vistados",
    "click #boton3": "vistatres"
  },

Also, how it has been commented it is important to add the library underscore.js next to backbone.js

    
answered by 22.06.2016 в 17:02