0

Hello I know that this question has been asked many times but there are too many opinions and arguments. I don't have the greatest experience to validate the answers so here it goes I'll explain what I'm looking for and perhaps you can point me to the right direction.

In my app I have created an object with some methods, most of them have a set of predefined default values, like so:

module.exports = {

    submit: function(options) {

        var defaults = {
            _id: 1453,
            text: 'Some text',
            dataObj:{
                links: 3532,
                arr: ['James','Paul','Lina'],
            },
            dims:{
                width: getClientWidth(),
                height: getClientHeight()
            }
        }

        options.extend(defaults);

        return sendData(defaults);

    }

    // other similar methods - functions

};

What I'm interested in is to extend the properties and attributes of the defaults local variable. As you can see defaults is a complex structured object. Keep in mind that options structure might be even more complex. So A simple shallow merge / copy might not be ideal here if I'm not mistaken.

Usage as you can imagine:

var app = {
   // stuff
}

app.fn = require('common/lib.js');

app.initialize(function(){
   var settings = {
      // hell here
   }
   app.fn.submit(settings)
})

Thank you in advance.

PS. No libraries are being used and I'm interested of in a pure javascript implementation of extend() function in any way.

0x_Anakin
  • 3,229
  • 5
  • 47
  • 86
  • Are you using NodeJS or running this in a browser? Anyway try: `options.extend(true, defaults);` it sets a 'deep copy' flag. Edit: atleast for a number of libaries it should. Not quite sure where your extend function is coming from. – Hless Sep 24 '13 at 08:27
  • I don't use a library this is fro a appcelerator project I'm working on and I'm looking for a ppure javascript solution – 0x_Anakin Sep 24 '13 at 08:33

1 Answers1

0

Similar question asked here: deep extend (like jQuery's) for nodeJS

Just copy the extend function from the accepted answer into your project, so that it is available within the correct scope. Then use it like so: options = extend(true, defaults, options);

Your settings object could look something like the following and will be merged on top of the defaults correctly:

var settings = {
  text: "Other text",
  dataObj:{
    links: 3531
  }
};
Community
  • 1
  • 1
Hless
  • 3,326
  • 20
  • 22