Question

I have the following javascript:

  if(i==1&&$('#ln').val()=='true')
    ops={
      xaxis: {show:false},
      yaxis: {show:false,
              transform: function (v) { return -v; },
              inverseTransform: function (v) { return -v; }}}
  else ops={xaxis: {show:false}, yaxis: {show:false}};
  $.plot($(gr), pdat,ops);

When I tried to make a string of ops I got errors on parsing it. I suppose it's because of the functions. How can I put together the options so I can add other options according to different conditions? In the example the idea is to avoid repeating xaxis: {show:false}, yaxis: {show:false}

Was it helpful?

Solution

You can populate the ops object with the common properties and then add others in your if statement:

  // initalize ops with common properties
  var ops = {
      xaxis: {show: false},
      yaxis: {show: false}
  };
  if (i == 1 && $('#ln').val() == 'true') {
      ops.yaxis.transform = function (v) { return -v; };
      ops.yaxis.inverseTransform = function (v) { return -v; };
  }
  $.plot($(gr), pdat, ops);

OTHER TIPS

If you have a more complicated scenario, I'd recommend jquery's extend method:

var ops = {
  xaxis: {show: false},
  yaxis: {show: false}
};
if (i == 1 && $('#ln').val() == 'true') {
    $.extend(true, ops, {
      yaxis: {
         transform: function (v) { return -v; },
         inverseTransform: function (v) { return -v; }
      }
    });
}

Ops is now:

{
  "xaxis":{
     "show":false
   },
  "yaxis":{
     "show":false,
     "transform": function (v) { return -v; },
     "inverseTransform": function (v) { return -v; }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top