Ad

How Can I Set A Parameter In Multiple Functions And Then Have It Switched And Persist

- 1 answer

I realize that is a poor title but it was the best I could come up with, let me see if I can explain it:

I have a chart, and because of the nature of the chart and the data, I am using two functions and hiding divs. Along with these two functions I have two different types of charts (candlestick and line). I need to be able to have someone set the 'type' (candle or line) of chart and then be able to change the time periods of the chart while the 'type' stays the same.

So far, my inclination is using a global 'type' variable but I understand that using a global isn't a great practice and it doesn't feel like the right solution even apart from the fact that it isn't working). The code is basically like this:

type = 'line';

function makeDayChart(type, days){
    if(type == 'line'){
    *make line chart*
  } else {
    *make candle chart*
  }
}

function makeHourChart(type, hours){
    if(type == 'line'){
    *make line chart*
  } else {
    *make candle chart*
  }
}

This approach makes some sort of sense to me, but I know it isn't the way to do it. I have been trying to research an approach for this, but haven't been able to find anything today, if you know any keywords or anything that would apply I'd appreciate it.

Here is a jsbin that is showing the code I've come up for this, it obviously isn't working, but...it is something.

THANKS for taking the time to read this.

http://jsbin.com/nusufohosi/1/edit?html,js,console,output


Taking into account @magreenberg's answer, I have tried to implement it. This is an update:

JSBin

Ad

Answer

It sounds like what you are looking for is a constructor function. JS constructors are the closest thing JS has to classes. For example, you have a constructor function that builds a graph and holds all it's attributes

// SETUP Chart constructor function
function Chart(type, time){
    this.type = type;
    this.time = time
}

Chart.prototype.buildChart = function(){
     if (this.time === "hour"){
        if (this.type === "line"){
            // build hour line chart
        } else if(this.type ==="candle"){
            // build hour candle chart
        }
     } else if (this.time === "days"){
        if (this.type === "line"){
            // build days line chart
        } else if(this.type ==="candle"){
            // build days candle chart
        }
     }
}

// Instantiate new object
var chartA = new Chart("line", "days");
var chartB = new Chart("chandle", "hours");

// call graph function to build object
chartA.buildChart();
chartB.buildChart();

Constructor functions can be difficult to understand. Especially when it comes to prototype chaining. Hopefully this gets you started in the right direction.

Ad
source: stackoverflow.com
Ad