Search code examples
javascriptjqueryparameter-passingobject-initialization

How to pass object/template as parameter in Javascript/jQuery


I'm attempting my first forray into jQuery. I'm trying to acheive the following, though I'm not sure of the terminology so will try to explain with an example using a kind of C#/pseudocode syntax.

Say I want an (anonymous) object as parameter, looking something like:

elemParameter {
    elemId,
    arg1,
    optionalArg2
}

and I want to pass an array/collection of these objects into my function

$(document).ready(function() {
    $.myFunction(
        new { Id = "div1", Color = "blue", Animal = "dog" },
        new { Id = "div3", Color = "green" },
        new { Id = "div4", Color = "orange", Animal = "horse" }
    );
}

and then in my function, I need to access each object of the collection, something like:

(function($) {
    $.myFunction(var elemParams) {
        foreach (param in elemParams) {
            $('#' + param.Id).onclick = function() {
                this.css('background-color', param.Color);
                alert(param.Animal ?? 'no animal specified');
            }
        }
    }
}

Can someone give me a few pointers to the correct syntax for passing parameters this way? Or suggest a better way of acheiving the same if this isn't the correct way to go about things in javascript.


Solution

  • Your syntax is just a bit off, it would look something like this:

    $(function() {
      function myFunction() {
        $.each(arguments, function(i, arg) {
          $('#' + arg.Id).click(function() {
            $(this).css('background-color', arg.Color);
            alert(arg.Animal || 'no animal specified');
          });
        });
      }
      myFunction({ Id: "div1", Color: "blue", Animal: "dog" },
                 { Id: "div3", Color: "green" },
                 { Id: "div4", Color: "orange", Animal: "horse" });​
    });
    

    You can try a demo here, the syntax style is called JavaScript object literal notation, that's what you're googling for when looking for more info around this :)

    Alternatively you can pass the objects in as an array if you want other arguments in addition to these, rather than using arguments directly.