I’m trying to experiment with Backbone.js and started by trying to reconfigure one of the standard ToDo tutorials.
This is the todo.js file I started with (not sure where I got it from):
$(function(){
AppView = Backbone.View.extend({
el: $(".content"),
events: {
"keypress #new-todo": "createOnEnter",
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
$("#todo-list").append("<li>"+$("#new-todo").val()+"</li>")
$("#new-todo").val('');
}
});
App = new AppView;
});
I wanted to see if I could figure out how to run everything through a router instead, so I tried this:
$(function(){
AppView = Backbone.View.extend({
el: $(".content"),
initialize: function(options) {
this.router = this.options.router;
},
events: {
"keypress #new-todo": "createOnEnter",
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
var term = $("$new-todo").val()
$("#todo-list").append("<li>"+term+"</li>")
$("#new-todo").val('');
this.router.navigate("stage/"+term);
},
});
// create router
AppRouter = Backbone.Router.extend({
initialize: function() {
// create view when router is initialized
new AppView({router : this});
},
routes: {
"stage/:stage" : "renderStage"
},
renderStage: function(stage) {
alert(stage);
}
});
App = new AppRouter;
});
But nothing seems to work. No events fire from the view, and no routes fire off either. When I debug in the console, I can access App which has the following parameters and methods:
_extractParameters
_routeToRegExp
bind
initialize
navigate
route
trigger
unbind
constructor
Several problems with your code:
var term = $("$new-todo").val()should bevar term = $("#new-todo").val()trueas the 2nd parameter torouter.navigate()to indicate you wish to trigger the routing.Backbone.history.start();in AppRouter’s.initialize()HERE is the working code.