【问题标题】:Updating Model from form in Backbone从 Backbone 中的表单更新模型
【发布时间】:2012-09-03 03:34:43
【问题描述】:

我正在使用 Backbone 和 Laravel 创建一个简单的应用程序来管理预订,并且我正在开发一个简单的表单来更新当前登录用户的用户数据。

我想知道,有没有比我以前的方法更好、更有效的方法来使用表单中的输入数据更新您的模型?

我在模型中创建了一个名为 update 的方法,它传递了一个表单的 DOM 对象。我认为这不是最好的方法。

任何帮助将不胜感激!

var Account = Backbone.Model.extend({

    url: "/settings/account",

    initialize: function()
    {

    },

    update: function(form)
    {
        this.set({
            first_name : form.find('#first-name').val(),
            last_name : form.find('#last-name').val(),
            email : form.find('#email').val(),
            landline: form.find('#landline').val(),
            mobile: form.find('#mobile').val()
        });

        return this.save();
    }

});

var user = new Account;

var AccountView = Backbone.View.extend({

    el: $("div.section"),

    template: _.template($("#account-template").html()),

    events: {
        "submit #account": "update"
    },

    initialize: function()
    {
        _.bindAll(this, 'render', 'update');
        this.render();
    },

    render: function()
    {
        $(this.el).html(this.template(this.model.toJSON()));
    },

    update: function()
    {
        var form = $(this.el).find('form#account');

        user.update(form);

        $(this.el).find('.alert-success').show();

        return false;
    }

});

var Router = Backbone.Router.extend({

    routes: {
        "account": "account"
    },

    account: function()
    {
        user.fetch({
            success: function()
            {
                return new AccountView({model:user});
            }
        });         
    }

});

【问题讨论】:

    标签: javascript backbone.js input views models


    【解决方案1】:

    当模型知道它的视图时,它被认为是糟糕的设计。我会更新由视图编排的模型。

    我认为最简单的方法是在视图中执行此操作:

    update: function()
    {
        var form = $(this.el).find('form#account');
        user.set({
            first_name : form.find('#first-name').val(),
            last_name : form.find('#last-name').val(),
            email : form.find('#email').val(),
            landline: form.find('#landline').val(),
            mobile: form.find('#mobile').val()
        });
    
        user.save();
        $(this.el).find('.alert-success').show();
        return false;
    }
    

    否则模型必须知道在哪里检索值。此外,当您有一天使用不同的视图时,您还必须更改模型类。

    【讨论】:

    • 我正要写同样的东西。与其将视图传递给用户,不如将用户模型传递给视图。然后您的视图可以使用update() 函数来设置用户的值。否则还不错。您可以set() 并通过执行user.save({'attribute':'value'}); 在一个呼叫(快捷方式)中保存您的数据
    • 是什么触发了视图上的“更新”调用?我有一个绑定到表单的视图,但我只想在用户单击提交按钮后使用 save() 更新模型并保存数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多