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.

masterdany88
  • 5,041
  • 11
  • 58
  • 132

5 Answers5

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).

George
  • 36,413
  • 9
  • 66
  • 103
  • Beat me to it. The most solid solution. Except for the default values which should probably be in sync with the expected datatypes. – Jonast92 Nov 26 '14 at 11:35
  • @Jonast92 Sure, but in this case I'm not going to go ahead and assume data-types. I will add a note though, thanks. – George Nov 26 '14 at 11:37
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);

    // ...
}
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
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/

Tejesh
  • 189
  • 2
  • 12
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});
dotty
  • 40,405
  • 66
  • 150
  • 195
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);
}
S.Pols
  • 3,414
  • 2
  • 21
  • 42