3

我有以下骨干模型

var Page = Backbone.Model.extend({
    defaults: {
        id: null,
        metadata: {
            name: '',
            title: '',
            ...
        },
        children: []
        parent: null
    },
    urlRoot: '/api/page',
    initialize: function () {}
});

当我保存以下表单时,我需要创建此表单的 JSON 表示并更新主干模型,然后再将其保存到服务器。我需要这样做,因为我的表单是动态创建的,所以我不能使用硬编码选择器来查找表单名称。下面是一个示例表格。

<form>
    <label>Name:</label>
    <input type="text" name="metadata.name" value="">
    <label>Title:</label>
    <input type="text" name="metadata.title" value="">
    <label>Slug:</label>
    <input type="text" name="metadata.slug" value="">
    <label>Url:</label>
    <input type="text" name="metadata.url" value="">
    <button type="submit">Save</button>
</form>

基于 HTML 表单数据更新主干模型的最有效方法是什么?

编辑

在 stackoverflow 找到了这个答案,使用方括号而不是对象之间的点。我认为这种技术效果很好,但也许有类似的方法可以使用点符号来序列化表单?

4

2 回答 2

2

I ended up using this neat little library for converting my form to a JavaScript object

于 2013-03-29T21:35:24.603 回答
-1

Having an idea what you have in mind, I'd just remove the Model defaults and leave the fields that's always there (or remove it period). Those fields are unknown at this point so setting defaults is not ideal in your case scenario. Technically speaking, the Model can just be updated to any field(s) that you want it to be and will adapt to whatever fields you feed it from the server.

The crucial stage is setting the Model initially since this dictates what attributes are contained within the Model. Since you mentioned that the form is created dynamically, you can create the Model via the JSON object that represents the data that goes along with the form you're rendering.

When it's time to save it back to the server, your Model will have all the attributes it needs to do the update. That's the first way.

model.save();

Or you can serialize the Form as a whole when it's time to save the changes. Basically, create a new Model at run-time.

var form= $('#myForm'); 
var data = JSON.stringify(form.serializeArray());

/**Create a new instance of the Model then and perform an update. */
var model = new MyModel(data);
model.save();
于 2013-03-29T19:43:34.127 回答