使用先前提交的数据重新填充Backbone表单集合

时间:2012-09-27 15:11:12

标签: backbone.js backbone-views

我可以将forms发布到我的数据库,我已经完成了后端功能,检查并看到我的Get函数返回了我提交的相同数据。但是,我无法理解如何在再次访问页面时呈现此数据。我错过了什么?目的是能够为可变的个人集合创建,读取,更新或删除(CRUD)一些个人联系人数据。

//Model
var PersonItem = Backbone.Model.extend({
    url: "/Application/PersonList",
    idAttribute: "PersonId",
    schema: {
        Title: {
            type: 'Select',
            options: function (callback) {
                $.getJSON("/Application/GetTitles/").done(callback);
            }
        },
        Salutation: { type: 'Select', options: ['Mr.', 'Mrs.', 'Ms.', 'Dr.'] }, 
        FirstName: 'Text',
        LastName: 'Text',
        MiddleName: 'Text',
        NameSuffix: 'Text',
        StreetAddress: 'Text',
        City: 'Text',
        State: {
            type: 'Select',
            options: function (callback) {
                $.getJSON("/Application/GetStates/").done(callback);
            }
        },
        ZipCode: 'Text',
        PhoneNumber: 'Text',
        DateOfBirth: 'Date',
    }
});
Backbone.Form.setTemplates(template, PersonItem);
//Collection
var PersonList = Backbone.Collection.extend({
    model: PersonItem
    , url: "/Application/PersonList"
});
//Views
var PersonItemView = Backbone.Form.extend({
    tagName: "li",
    events: {
        'click button.delete': 'remove',
        'change input': 'change'
    },
    initialize: function (options) {
        console.log("ItemView init");
        PersonItemView.__super__.initialize.call(this, options);
        _.bindAll(this, 'render', 'remove');
        console.log("ItemView set attr = " + options);
    },
    render: function () {
        PersonItemView.__super__.render.call(this);
        $('fieldset', this.el).append("<button class=\"delete\" style=\"float: right;\">Delete</button>");
        return this;
    },
    change: function (event) {
        var target = event.target;
        console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value);
    },
    remove: function () {
        console.log("delete button pressed");
        this.model.destroy({ success: function () { alert('person deleted successfully'); } });
        return false;
    }
});

var PersonListView = Backbone.View.extend({
    el: $("#application_fieldset"),

    events:
        {
            'click button#add': 'addPerson',
            'click button#save': 'save2db'
        },
    initialize: function () {
        console.log("PersonListView Constructor");
        _.bindAll(this, 'render', 'addPerson', 'appendItem', 'save');
        this.collection = new PersonList();
        this.collection.bind('add', this.appendItem);
        //this.collection.fetch();
        this.collection.add([new PersonItem()]);
        console.log("collection length = " + this.collection.length);
    },
    render: function () {
        var self = this;
        console.log(this.collection.models);
        $(this.el).append("<button id='add'>Add Person</button>");
        $(this.el).append("<button id='save'>Save</button>");
        $(this.el).append("<fieldset><legend>Contact</legend><ul id=\"anchor_list\"></ul>");
        _(this.collection.models).each(function (item) {
            self.appendItem(item);
        }, this);
        $(this.el).append("</fieldset>");
    },
    addPerson: function () {
        console.log("addPerson clicked");
        var item = new PersonItem();
        this.collection.add(item);
    },
    appendItem: function (item) {
        var itemView = new PersonItemView({ model: item });
        $('#anchor_list', this.el).append(itemView.render().el);
    },
    save2db: function () {
        var self = this;
        console.log("PersonListView save");
        _(this.collection.models).each(function (item) {
            console.log("item = " + item.toJSON());
            var cid = item.cid;
            console.log("item.set");
            item.set({
                Title: $('#' + cid + '_Title').val(),
                Salutation: $('#' + cid + '_Salutation').val(),
                FirstName: $('#' + cid + '_FirstName').val(),
                LastName: $('#' + cid + '_LastName').val(),
                MiddleName: $('#' + cid + '_MiddleName').val(),
                NameSuffix: $('#' + cid + '_NameSuffix').val(),
                StreetAddress: $('#' + cid + '_StreetAddress').val(),
                City: $('#' + cid + '_City').val(),
                State: $('#' + cid + '_State').val(),
                ZipCode: $('#' + cid + '_ZipCode').val(),
                PhoneNumber: $('#' + cid + '_PhoneNumber').val(),
                DateOfBirth: $('#' + cid + '_DateOfBirth').find('input').val()
            });

            if (item.isNew()) {
                console.log("item.isNew");
                self.collection.create(item);
            } else {
                console.log("!item.isNew");
                item.save();
            }
        });
        return false;
    }
});
var personList = new PersonList();
var view = new PersonListView({ collection: personList });
personList.fetch({ success: function () {
    $("#application_fieldset").append(view.render());
}
});

1 个答案:

答案 0 :(得分:0)

我弄清楚了我的错误。我需要删除在PersonListView初始化中创建一个新的PersonList。

      this.collection = new PersonList();//removed this line

希望此代码可以帮助拥有骨干表单的人。 :)