gpt4 book ai didi

javascript - 初始化路由器内部的 View

转载 作者:行者123 更新时间:2023-11-29 22:27:33 24 4
gpt4 key购买 nike

我正在尝试使用 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;

});

但似乎没有任何效果。没有事件从 View 中触发,也没有路由触发。当我在控制台调试时,我可以访问具有以下参数和方法的App:

_extractParameters
_routeToRegExp
bind
initialize
navigate
route
trigger
unbind
constructor

最佳答案

你的代码有几个问题:

  • var term = $("$new-todo").val() 应该是 var term = $("#new-todo").val()
  • 您需要将 true 作为第二个参数传递给 router.navigate() 以表明您希望触发路由。
  • 正如 rkw 所指出的,不要忘记在 AppRouter 的 .initialize() 中调用 Backbone.history.start();/li>

HERE 是工作代码。

关于javascript - 初始化路由器内部的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com