Search code examples
javascriptjquerybackbone.js

_.extend doesn't shallow copy elements to destination properly


I've just started to write a Backbone library which goes like this,

(function() {
    var root = this;

    if(root && !root.Backbone) {
        console.log('BackboneJS does not exist!.');
    } else {
        Backbone = root.Backbone;
    }

    var Form = Backbone.View.extend({
        events: {
            'submit': function(event) {
                this.trigger('submit', event);
            }
        },
        initialize: function(options) {
            var self = this;
            var options = this.options = _.extend(options, {
                submitButton: false
            });
        }
    });
    Backbone.Form = Form;
})();

And I'm invoking this through jQuery (in my index.html) like this,

$(document).ready(function(){
  var myForm = new Backbone.Form({
  options: {
    hasTopButtons : true,
    hasEdit: false,
    hasPrint: true
  }
});

But, when I use the _.extend function to shallow copy additional keys to the options it doesn't seems to me including the new key into the existing options array, instead it creates a new one outside of the options array like this,

What is currently happening

Instead of the below structure.

How I expect that to come

Can someone help me to find out what is going wrong here?


Solution

  • You're invoking the function incorrectly. You want:

    $(document).ready(function(){
      var myForm = new Backbone.Form({
        hasTopButtons : true,
        hasEdit: false,
        hasPrint: true
      });
    });
    

    Your code explicitly passes an object that has a single property called "options".

    Also, in your "initialize" function, there's a spurious var declaration:

            var options = this.options = _.extend(options, {
                submitButton: false
            });
    

    That should probably be

            this.options = _.extend({}, options, {
                submitButton: false
            });
    

    The _.extend function modifies the first object, and you probably don't want to be messing with client objects like that. Thus, you can pass in a new empty object, and _.extend() will shallow-copy all the client properties into it.