Repopulating a collection of Backbone forms with previously submitted data

Posted by Brian Wheat on Stack Overflow See other posts from Stack Overflow or by Brian Wheat
Published on 2012-09-27T15:11:12Z Indexed on 2012/09/27 15:37 UTC
Read the original article Hit count: 304

Filed under:
|

I am able to post my forms to my database and I have stepped through my back end function to check and see that my Get function is returning the same data I submitted. However I am having trouble understanding how to have this data rendered upon visiting the page again. What am I missing? The intention is to be able to create, read, update, or delete (CRUD) some personal contact data for a variable collection of individuals.

//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());
}
});

© Stack Overflow or respective owner

Related posts about backbone.js

Related posts about backbone-views