1

我想创建一个包含文本字段和复选框列表的表单。

使用带有_.each()语句的下划线模板函数,我可以得到它的呈现。

当我单击保存按钮时,我得到了模型(带有文本字段),但复选框的数组不在它应该在的位置......

这是我的视图模型:

window.SpotEditView= Marionette.View.extend({

    initialize: function () {
        var featureList = ['Rail', 'Curb','Pipe'];
        //this.el = this.compiledTemplate(this.model.toJSON());
        var viewModel = this.model.toJSON();
        viewModel.features = featureList;

        $(this.el).html( _.template(htmlBody, viewModel));
        return;
    },

    render: function () {
        return this;
    },

    events: {
        "change"        : "change",
        "click .save"   : "beforeSave",
        "click .delete" : "delete",
        "drop #picture" : "dropHandler"
    },

    beforeSave: function () {
        var self = this;
        var check = this.model.validateAll();
        if (check.isValid === false) {
            utils.displayValidationErrors(check.messages);
            return false;
        }
        // Upload picture file if a new file was dropped in the drop area
        if (this.pictureFile) {
            this.model.set("picture", this.pictureFile.name);
            utils.uploadFile(this.pictureFile,
                function () {
                    self.save();
                }
            );
        } else {
            self.save();
        }
        return false;
    },

    save: function () {
        var self = this;
        this.model.save(null, {
            success: function (model) {
                self.render();
                var point = model.toMarker();
                app.mapView.model.markers.add(point);
                app.navigate('map', true);
                app.mapView.openInfo(point);

            },
            error: function () {
                utils.showAlert('Error', 'An error occurred while trying to save this item', 'alert-error');
            }
        });
    }
});

这是我的 html 模板的相关部分:

<% _.each(features, function(f,key) { %>
<label class="checkbox">
    <input type="checkbox" name="features[<%= key-1 %>]" value="<%= f %>">
    <%= f %>
</label>
<% }); %>

保存函数接收的模型如下所示:

{..
    attributes:{ ...
        features:[],
        features[1]:'Dick',
        ...
    }
}

似乎主干“表单解析器”无法处理数组。

这种方法有修复或更好的解决方案吗?

4

0 回答 0