Question

I have one main home page in my application and another page for each post that can be accessed through a list displayed in the home page..

this is how my router looks like :

var AppRouter = Backbone.Router.extend({

    initialize: function(){
        this.model = new model();
        this.collection = new collection();
    },


    routes: {
        "" : "showForm",
        "post/:id" : "showPost"
    },


    showPost: function(id){
        var curmodel = this.collection.get(id);
        var post = new postView({model:curmodel});
        post.render();
        $(".maincontainer").html(post.el);

    },

    showForm : function(){
        var qcView = new qcV({model:this.model, collection:this.collection});
        qcView.render()
        $(".maincontainer").html(qcView.el);
    }
});

this is what one of the links to the posts in this list looks like

<h2><a id= "<%=_id%>" href="#post/<%=_id%>"><%=name%></h2></a>

my first question is: Is it dangerous to link pages with a hash-based URL in this manner?

my second question is: I am having no problem navigating to a posts view if I click one of the links in my home page. I my url successfully changes to something like http://127.0.0.1:3000/#post/51ffdb93c29eb6cc17000034 and that specific post's view is rendered. However at that point if I refresh the page, or if I directly type http://127.0.0.1:3000/#post/51ffdb93c29eb6cc17000034to my URL bar the this.collection.get(id) method in my showPost method in the router returns undefined. Can anyone help me figure out why this is the case?

I checked couple times that my initialize method gets called both times, and my collection and model is created successfully

Was it helpful?

Solution

For #2, you are most likely not fetching the collection on the "post" route. Try fetching the collection (if it does not exist) and then call render. That should do the trick!

OTHER TIPS

I think @Trunal's on the right path for the 2nd question. For the first, no, it's not "dangerous". You're not really doing anything different than you would with a classic server-side app, passing information to the server via GET to retrieve info. In my opinion, this should be the preferred approach to implementing routes (rather than attempting to trigger backbone.history.navigate manually, as it avoids all kinds of setup and eventing issues that might otherwise occur).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top