简体   繁体   English

如何使用 Backbone.js 捕获表单提交

[英]How to catch form submit with Backbone.js

When I test and click my apply button after I put in data in my input fields, I get a file not found error .当我在输入字段中输入数据后进行测试并单击apply按钮时,出现文件未找到错误

The Login button is a dummy button with no functionality to it. Login按钮是一个虚拟按钮,没有任何功能。 I want to only display an alert box that says "You logged in as (user name here) Succesfully!!!"我只想显示一个警告框,上面写着“您以(此处的用户名)成功登录!!!” after apply is clicked.单击应用后。

var Credentials = Backbone.Model.extend({});

var LoginView = Backbone.View.extend({
  el: $("#login-form"),

  events: {
    "click #login": "login"
  },

  initialize: function(){
    var self = this;

    this.firstname = $("#username");
    this.lastname = $("#lastname");
    this.number = $("#number");
    this.username = $("#username");
    this.password = $("#password");

    this.firstname.change(function(e){
      self.model.set({firstname: $(e.currentTarget).val()});
    });

    this.lastname.change(function(e){
      self.model.set({lastname: $(e.currentTarget).val()});
    });

    this.number.change(function(e){
      self.model.set({number: $(e.currentTarget).val()});
    });

    this.username.change(function(e){
      self.model.set({username: $(e.currentTarget).val()});
    });

    this.password.change(function(e){
      self.model.set({password: $(e.currentTarget).val()});
    });
  },

  login: function(){
    var firstn= this.model.get('firstname');
    var lastn= this.model.get('lastname');
    var numb= this.model.get('number');
    var user= this.model.get('username');
    var pword = this.model.get('password');

    alert("You logged in as " + user + "Succesfully!!!");

    return false;
  }
});

window.LoginView = new LoginView({model: new Credentials()});
});

<form action="/login" id="login-form" align="left">
    <h1> Your Registration Form:</h1>

    First Name <input type="text" id="firstname" placeholder="First Name">
    Last Name <input type="text" id="lastname" placeholder="Last Name">
    Phone No. <input type="text" id="number" placeholder="1(555)555-5555">
    UserName <input type="text" id="username" placeholder="UserName">
    Password <input type="password" id="password" placeholder="Password">

    <button id="login" onclick="">Apply</button>
    <!-- dummy button  -->
    <button id="login-button">Login</button>
</form>

Why a file not found error?为什么找不到文件错误?

You get a file not found error because the form is submitted and the action is "/login" with the default method being a GET request, so the submit makes a GET request to the login page but it doesn't exist on the server.由于表单已提交并且操作为"/login" ,默认方法为GET请求,因此您收到文件未找到错误,因此提交向login页面发出GET请求,但它在服务器上不存在。 The server returns a File not found error.服务器返回File not found错误。

How to prevent the submit?如何防止提交?

You need to stop the submit with JavaScript.您需要使用 JavaScript 停止提交。 To do that, first catch the submit event, then call .preventDefault() on the submit event object.为此,首先捕获提交事件,然后在提交事件对象上调用.preventDefault()

How to catch the submit event with Backbone?如何使用 Backbone 捕获提交事件?

Backbone offers the events property on views. Backbone 提供关于视图的events属性

The events hash (or method) can be used to specify a set of DOM events that will be bound to methods on your View through delegateEvents .事件哈希(或方法)可用于指定一组 DOM 事件,这些事件将通过delegateEvents绑定到您的 View 上的方法。

The following is the simplest way of catching a submit event, granted the root element of the view is the form, like in your code.以下是捕获submit事件的最简单方法,授予视图的根元素是表单,就像在您的代码中一样。

events: {
    "submit": "onSubmit",
},

onSubmit: function(e) {
    // `e` being a standard DOM event
    e.preventDefault();
}

Here I simplified your view:在这里,我简化了您的观点:

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);
    }
});

Specify the form buttons type attribute as it's submit by default.指定表单按钮类型属性,因为它默认submit So making the #login-button a type="button" ensures it won't trigger a submit.因此,将#login-button设为type="button"可确保它不会触发提交。

<button type="submit" id="login">Apply</button>

<!-- dummy button  -->
<button type="button" id="login-button">Login</button>

Why isn't it working when using the exact code above?为什么在使用上面的确切代码时它不起作用?

Notice that the root element of the view is specified with the el property .请注意,视图的根元素是用el属性指定的。

In your initial code, you're using jQuery's core function to find and pass the form element to the view.在您的初始代码中,您使用jQuery 的核心函数来查找表单元素并将其传递给视图。 But for it to work, the form element must exist before running the JS of the view.但是为了让它工作,在运行视图的 JS 之前表单元素必须存在

So the HTML page structure should look something like this:所以 HTML 页面结构应该是这样的:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM