0

I would like to know how to create jquery function that I could then call with parameters name and value declared in it.

Instead of giving in correct order variables to function like this:

myFunction("My function name",true,false);

I would like to give to function something like that:

function({
  displayName: "My function name",
  editable: true,
  displayForm: false;
})

where order of parameters dosnt matter, cause I am giving it by theier name.

I've saw that configuration in every jquery lib (jqPlot,JqGrid,noty etc.) Here is example:

$(document).ready(function(){
  var plot1 = $.jqplot('chart1', [cosPoints], {  
      series:[{showMarker:false}],
      axes:{
        xaxis:{
          label:'Angle (radians)'
        },
        yaxis:{
          label:'Cosine'
        }
      }
  });
});

--Edited--

I have my own js function to print trees from json, but I have so much parameters, that it is so hard to read and edit.

4
  • Do you want to create a function or a jquery extension? Commented Nov 26, 2014 at 11:30
  • 1
    Just pass the object as a parameter and use it within the function. Commented Nov 26, 2014 at 11:31
  • Are you trying to create your own jQuery plugin? Commented Nov 26, 2014 at 11:32
  • Did you see this : stackoverflow.com/questions/12093192/… Commented Nov 26, 2014 at 11:33

5 Answers 5

3

There is no reason why you can't do what you are asking, just have your function expect an object literal:

function MyFunction(o){
    // Do whatever you need to do with your object properties,
    // like set some corresponding scoped variables.
    // 0 would be their default values, change as appropriate.
    var displayName = o.displayName || 0,
        editable = o.editable || 0,
        displayForm = o.displayForm || 0;
}

Then call it how you wanted:

myFunction({
    displayName: "My function name",
    editable: true,
    displayForm: false;
});

For the record, there is no jQuery functionality here. This is all vanilla JavaScript.


Note, if you are using jQuery, you could check that the parameter is in fact an object literal before going on to carry out functionality, with $.isPlainObject(o).

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it. The most solid solution. Except for the default values which should probably be in sync with the expected datatypes.
@Jonast92 Sure, but in this case I'm not going to go ahead and assume data-types. I will add a note though, thanks.
2

Just declare your function taking an object as the argument :

function myFunction(obj) {
    if(obj.displayName) {
    // do something with obj.displayName
    }

    // ....
}

And you can call it as you indicated :

myFunction({
    displayName: "My function name",
    editable: true,
    displayForm: false;
});

or even with this :

myFunction({
    editable: true,
    displayForm: false;
});

In order to test if a property exists in your object passed as the argument, just put the test as I have done : obj.myProperty.

Another point is that you can put default values with $.extend :

function myFunction(obj) {
    var myDefaults = {
        displayName: "My default name",
        editable: false
    };

    // Fill `obj` with the missing values that have to be supplied
    // and that we take in `myDefaults`
    $.extend(obj, myDefaults);

    // ...
}

Comments

0

jQuery Extension

jQuery.fn.extend({
    zigzag: function () {
        var text = $(this).text();
        var zigzagText = '';
        var toggle = true; //lower/uppper toggle
            $.each(text, function(i, nome) {
                zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                toggle = (toggle) ? false : true;
            });
    return zigzagText;
    }
});

console.log($('#tagline').zigzag());
//output: #1 jQuErY BlOg fOr yOuR DaIlY NeWs, PlUgInS, tUtS/TiPs & cOdE SnIpPeTs.

//chained example
console.log($('#tagline').zigzag().toLowerCase());
//output: #1 jquery blog for your daily news, plugins, tuts/tips & code snippets.

For more references you can check : http://www.sitepoint.com/5-ways-declare-functions-jquery/

Comments

0

The {} is just shorthand for an object.

Take this example

var person = {firstName:"John", lastName:"Doe", age:46};

If you pass that as an unnamed object to a function, you can pick our the values from that. For example:

function myFunc( myArg ){
    alert( myArg.firstName );
}

and call it with

myFunc({firstName:"John", lastName:"Doe", age:46});

Comments

0

It's is working properly if you just pass your object as parameter to the function.

test({a:"TestA", b:"TestB"});

function test(object)
{
    alert(object.a);
    alert(object.b);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.