1

I am developing a small JavaScript Framework, I need to know how to add some options to a function, so the user can set his own settings for a particular method.

This is a sample function method i have created

$.prototype = {
  setCenter: function() {

        this.e.style.position = 'absolute';
        this.e.style.top = '50%';
        this.e.style.left = '50%';
        this.e.style.marginLeft = '-50px';
        this.e.style.marginTop = '-50px';
        return this;



    }
};

I am expecting this to be developed to handle the below options sets.

*I am not using JQuery, I need a pure JavaScript Solution for this. This is an example code, maybe not the real thing , but just get the idea.

$('sampleDiv').setCenter({
              animate:true, fade:true
              });

Help me solve this problem, i appreciate anyone who tries to answer this. Thank you !

10
  • 1
    Your second code doesn't make any sense. Commented Jul 31, 2013 at 11:57
  • Are you using jquery plugin? Commented Jul 31, 2013 at 12:01
  • 2
    It sounds like you are looking for an option similar to jQuery's "extend", eg: $.extend({foo: "a", "bar": "b"}, {foo: "extended"}) => {foo: "extended", "bar": "b"}. Would that be accurate? Commented Jul 31, 2013 at 12:02
  • Yeah Something like that, How can i implement that? Commented Jul 31, 2013 at 12:05
  • @AndrewDex this can be implemented using a simple for...in loop to copy parameters from one object to the other one. Commented Jul 31, 2013 at 12:06

3 Answers 3

1

You could implement your main function this way :

this.doSomething = function() {
    var getDefault = function(args, property, otherwise) {
            return args[property] !== undefined ? args[property] : otherwise;
    };

    this.foo = getDefault(arguments, 'foo', 42);
    this.bar = getDefault(arguments, 'bar', false);
};

So you can call it like that :

this.doSomething({foo: true});
Sign up to request clarification or add additional context in comments.

Comments

1

Copied the code from this answer

function extend(){
    for(var i=1; i<arguments.length; i++)
        for(var key in arguments[i])
            if(arguments[i].hasOwnProperty(key))
                arguments[0][key] = arguments[i][key];
    return arguments[0];
}

This function can be used for any number of objects.

var newObj = extend(obj1, obj2, obj3, ...);

OR

var newObj = extend({}, obj1, obj2, obj3, ...); 

Comments

1
$.prototype = {
  setCenter: function(offset) {

        this.e.style.position = 'absolute';
        this.e.style.top = '50%';
        this.e.style.left = offset + 50 + '%';
        this.e.style.marginLeft = '-50px';
        this.e.style.marginTop = '-50px';
        return this;
    }
};

Use like this

this.setcenter(23);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.