events: {
"submit": "onSubmit",
},
onSubmit: function(e) {
// `e` being a standard DOM event
e.preventDefault();
}
我在这里简化了你的看法:
var LoginView = Backbone.View.extend({
// Put the string into a template to ease the manipulation later on.
template: _.template("You logged in as <%= username %> and a password of <%= password %>\nFirstName:<%= firstname %>\nLastName:<%= lastname %>\nNumber:<%= number %>"),
el: $("#login-form"),
events: {
// listen for the submit event of the form
"submit": "onSubmit",
// listen to events from here
"change #username": 'onUsernameChange'
},
initialize: function() {
// it's a good idea to cache jQuery objects like this.
this.firstname = $("#username");
this.lastname = $("#lastname");
this.number = $("#number");
this.username = $("#username");
this.password = $("#password");
// but avoid extensive `change` listeners as it's inefficient and
// useless in this case. If you want to listen to changes, do it
// in the events hash, like the "onUsernameChange" example.
},
onSubmit: function(e) {
// prevent the submit and do what you want instead
e.preventDefault();
// Set directly with an object, it's quick and clean.
this.model.set({
firstname: this.firstname.val(),
lastname: this.lastname.val(),
number: this.number.val(),
username: this.username.val(),
password: this.password.val()
});
// use the template for the alert.
alert(this.template(this.model.toJSON()));
},
onUsernameChange: function(e) {
// no need for jQuery for a trivial value retrieval
console.log(e.currentTarget.value);
}
});
<html>
<head>
<!-- head stuff like CSS, title, etc. -->
</head>
<body>
<form id="login-form">
<!-- rest of the form goes here -->
</form>
<!-- Load the scripts here -->
<script src="libs/jquery/dist/jquery.js"></script>
<script src="libs/underscore/underscore.js"></script>
<script src="libs/backbone/backbone.js"></script>
<!-- then your own code can go here, or into another js file. -->
<script>
// your view, etc.
</script>
</body>
</html>
1条答案
按热度按时间jc3wubiy1#
为什么会出现“找不到文件”错误?
您会收到一个找不到文件的错误,因为表单已经提交,操作是
"/login"
,默认方法是GET
请求,所以提交操作会向login
页面发出GET
请求,但该页面在服务器上不存在。服务器返回一个File not found
错误。如何防止提交?
你需要用JavaScript来停止提交,首先捕获submit事件,然后在submit事件对象上调用
.preventDefault()
。如何使用Backbone捕获提交事件?
Backbone 网在视图上提供
events
属性。events散列(或方法)可用于指定一组DOM事件,这些事件将通过
delegateEvents
绑定到视图上的方法。下面是捕获
submit
事件的最简单方法,假定视图的根元素是表单,就像在代码中一样。我在这里简化了你的看法:
将表单按钮的类型属性指定为默认的
submit
,因此将#login-button
设置为type="button"
可以确保它不会触发提交。为什么在使用上面的代码时无法正常工作?
请注意,视图的根元素是使用
el
属性指定的。在初始代码中,您使用jQuery's core function来查找表单元素并将其传递给视图。但要使其工作,表单元素必须在运行视图的JS之前存在。
因此,HTML页面结构应类似于: