在路由器中初始化视图
问题描述:
我试图用Backbone.js进行实验,并尝试重新配置其中一个标准ToDo教程。在路由器中初始化视图
这是todo.js文件我开始用(不知道我来自哪里得到它):
$(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;
});
我想看看,如果我能想出如何运行通过路由器来代替一切,所以我试过这个:
$(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;
});
但似乎没有任何工作。没有任何事件从视野中消失,也没有任何路线起火。当我在控制台的调试,我可以访问App
它具有以下参数和方法:
_extractParameters
_routeToRegExp
bind
initialize
navigate
route
trigger
unbind
constructor
答
的几个问题与您的代码:
-
var term = $("$new-todo").val()
应该var term = $("#new-todo").val()
- 您需要通过
true
作为第二个参数来router.navigate()
以表明您希望触发路由。 - 作为RKW指出,不要忘记调用
Backbone.history.start();
在AppRouter的.initialize()
HERE是工作代码。
答
我想你应该写
this.view =新APPVIEW({路由器:此}) ;
代替
新APPVIEW({路由器:此});
因为在您的代码中,AppView实例将在创建后立即被垃圾收集,因为您不需要引用它。
+0
'AppView'无法收集垃圾,因为它被使用 - 例如,有处理程序注册。 – kubetz 2011-12-22 10:34:38
尝试启动历史记录:Backbone.history.start();在实例化路由器后 – rkw 2011-12-22 07:42:28