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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With