初始化路由器内部的视图

Initializing views inside routers

本文关键字:视图 内部 路由器 初始化      更新时间:2023-09-26

我正在尝试用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指出的,不要忘记在approouter的.initialize()
  • 中调用Backbone.history.start();
这里的

工作代码。

我觉得你应该写

代替

new AppView({router: this});

因为在您的代码中,AppView实例将在创建后被垃圾收集,因为您没有保存对它的引用。