如何使用Backbone将数据从HTML表单添加到数据库?

时间:2014-04-22 22:41:45

标签: javascript python backbone.js

我有下一个问题 - 我需要将HTML表格中的数据加入我的服务器(Python Flask)。 但似乎没有任何反应,也没有工作。 我做错了什么? 我的模特可能有些不好吗?

我的代码: 型号:

define(["underscore", "backbone", "jquery"],

    function(_, Backbone, $) {
        return Backbone.Model.extend({

            urlRoot: "/adduser",

            defaults: {
                "email": "",
                "f_name": "",
                "id_role": 0,
                "l_name": "",
                "login": "",
                "password": "",
                "status": 1
            }
        });
    });

查看:

define([
        "underscore",
        "backbone",
        "jquery",
        "text!pages/RestaurantPage/templates/AdminTemplate.html",
        "pages/RestaurantPage/models/User"

    ],

    function(_, Backbone, $, AdminTemplate, User) {
        return Backbone.View.extend({

            events: {
                events: {
                    'submit #new_user': 'save'
                }
            },

            initialize: function() {
                this.collection = new User();
                this.collection.on("change", this.collection.save());
            },

            el: $('#content'),

            save: function(e) {
                alert('ok"');
                var userInfo = {
                    email: this.$('#email').val(),
                    l_name: this.$('#l_name').val(),
                    f_name: this.$('#f_name').val(),
                    login: this.$('#login').val(),
                    password: this.$('#password').val(),
                    id_role: this.$('#id_role').val(),
                    status: this.$('#status').val()

                };
                this.collection.save(userInfo);

            },
            render: function() {

                this.$el.html(AdminTemplate);

            }
        });
    });

我的表单有id" new_user"和模型中的字段相同。

UPD:谢谢大家!我知道怎么做!

2 个答案:

答案 0 :(得分:0)

您的视图代码中有一些奇怪之处。在initialize()内,您通过调用模型的this.collection.on()函数调用save()。使用this.collection.on()时,您需要传递对save函数本身的引用,而不是对函数(save())的调用。

我也猜你的意思是在视图上调用save函数,而不是模型。我在这里更新了代码:

define([
        "underscore",
        "backbone",
        "jquery",
        "text!pages/RestaurantPage/templates/AdminTemplate.html",
        "pages/RestaurantPage/models/User"

    ],

    function(_, Backbone, $, AdminTemplate, User) {
        return Backbone.View.extend({

            // ...

            initialize: function() {
                this.collection = new User();
                // Pass in a reference to the save function
                this.collection.on("change", this.save, this);
            },

            // ...
        });
    });

答案 1 :(得分:0)

错误地,您已定义events两次&在彼此内。

任何控制台错误? &安培;将定义更改为仅包含一个事件定义,如下所示:

 return Backbone.View.extend({
            events: {
                'submit #new_user': 'save'
            },
            initialize: function() {
   //... remaining stuff goes here