Search code examples
javascriptdombackbone.jsbackbone-viewsbackbone.js-collections

Backbone - Get user's selected data from DOM or Collection


I have one Backbone Collection (named themeCollection) which items are listed on the webpage (DOM). The user can select one item from that list. I need to save user's selected item into the database together with other information. It comes out two ways from my head to implement this feature.

enter image description here

1) Get the selected list item from the DOM (by jquery)

addCard: function(e) {
            e.preventDefault();

            var formData = {};

            // Get data from the form
            $( '#modal-new-card form' ).children( 'input' ).each( function( i, el ) {
                if ( $(el).val() != '' ) {
                    formData[ el.id ] = $(el).val();
                }
                $(el).val('');
            });


            // Get selected listed item from the DOM.
            formData['theme'] = this.$el.find('div.colorSelected').attr('color');

            // Code for saving into the database
            // ...

        }

2) Get the selected list item from the Backbone Collection

addCard: function(e) {
        e.preventDefault();

        var formData = {};

        $( '#modal-new-card form' ).children( 'input' ).each( function( i, el ) {
            if ( $(el).val() != '' ) {
                formData[ el.id ] = $(el).val();
            }
            $(el).val('');
        });

        formData['theme'] = this.themeCollection.findWhere({selected: true});
    }

The first way seems to me a little awkward. It touches DOM so it closely coupled upon the DOM. That's not good. Whenever the CSS class is changed, my app would be stopped working.

The second way would be a little more jobs to be done. I have to change themeModel's selected attribute to be true whenever the user clicks. When changing, I also have to set false to selected attributes of all other models in the collection.

Which way would be the better choice? If you have any other ways, please share me and suggest me.


Solution

  • It appears you need to learn more about Backbone, but I'll try to help...


    You should be using a Model for maintaining the form data and add events via View to update model when things change. Upon submit, you can call model.toJSON() to save to the DB.

    var NewCard = Backbone.Model.extend({
    
        defaults: {
            question: '',
            explanation: '',
            color: 'Blue'
        }
    
    })
    

    Then setup a collection to hold the colors to select

    var colors = new Backbone.Collection([
      {color: 'Blue'},
      {color: 'Gray'}
    ]);
    

    Here is a working example

    preview

    The example is far from complete, but should give you a picture.