Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.history has already been started

I am getting an error "Backbone.history has already been started" on my Backbone.js app. Here's my code.

(function ($) {
    // model for each article
    var Article = Backbone.Model.extend({});

    // collection for articles
    var ArticleCollection = Backbone.Collection.extend({
        model: Article
    });

    // view for index page
    var MainView = Backbone.View.extend({
        el: $('#wrapper'),
        render: function (){
            var template = Handlebars.compile($("#main_hb").html());
            $(this.el).find('#main_content').html(template);
            return this;            
        }   
    });

    // view for listing blog articles
    var ArticleListView = Backbone.View.extend({
        el: $('#wrapper'),
        render: function(){
            var js = this.model.toJSON();
            var template = Handlebars.compile($("#articles_hb").html());
            $(this.el).find('#main_content').html(template({articles: js}));
            return this;    
        }
    });

    // main app
    var ArticleApp = Backbone.Router.extend({
        // setup routes
        routes: {
            ""  : "index",
            "blog"  : "blog"
        },          
        index: function(){
            var main = new MainView({});
            main.render();
            return this;
        },          
        blog: function(){
            $.ajax({
                url: 'blogs/articles', 
                dataType: 'json',
                data: {},
                success: function(data)
                {
                    var articles = new ArticleCollection(data);
                    var view = new ArticleListView({model: articles});
                    view.render();
                }       
            });
            return this;
        }

    });

    // let's start the app!
    articleApp = new ArticleApp();
    Backbone.history.start();

})(jQuery);

The app itself seems like it's working fine. But that error in Chrome is mysterious.

like image 352
ericbae Avatar asked Sep 09 '11 14:09

ericbae


2 Answers

12/30/2013 UPDATE: looks like this might be a common issue, i decide to bold the reason.

I ran into same issue and solved it. The reason is I

imported the js file twice

So I may suggest you check the page which contains this script see if it was introduced twice.

like image 79
yujingz Avatar answered Nov 10 '22 04:11

yujingz


Yujings said it right! It imported the js twice. updated My "fix" (is definitely more of a workaround) was to place this in the router.

Backbone.history.stop();
Backbone.history.start();

Probably not the most ideal, but it got the job done in a naive fashion.

like image 22
Tyler Davis Avatar answered Nov 10 '22 04:11

Tyler Davis