JavaScript OOP development in Sharepoint

I am really trying to grasp the concept of JavaScript OOP.  I have a SharePoint site and I want to implement creating instances from an object but I'm having a challenging time.

Here's what i'm trying to do.  I want to create a jqplot chart that will show the number of trucks for each county.  Here's my list
I basically need to loop through the items and add up the number of trucks for each county.  The pie chart will look like this but be dynamic.

This is what I have so far. I want to use javascript factory pattern and also prototypes.

 
function getListItems(url, listname, complete, failure) {

    // Executing our items via an ajax request
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (data) {
            failure(data);
        }
    });
	
 function complete(data) {
 
 for (i=0;i<=data.length; i++)
 {
	var jqPlotdata = new newTruck({
		state: data.d.results[i].State,
		town: data.d.results[i].Town,
		county: data.d.results[i].county,
		numberOfTrucks: data.d.results[i].numberOfTrucks	
	});
 }
 }
 
function failure(data) {
 alert("Operation failed.");
 }
 
 function newTruck(param) {
	this.state = param[0];
	this.town = param[1];
	this.county = county[2];
	this.numberOfTrucks = county[3];
	icTrucks.countArray = [];
 }
 newTruck.prototype.getCount = function () {
 // not sure but do something
 }

}

Open in new window


Can someone please help me connect the dots?

Thanks
LVL 5
IsaacSharePoint Client Side DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Just trying to understand why you are doing it that way?

Why not simply return the required object to your AJAX call using JSON. This can then be sent directly to jqPlot as per this example here http://www.jqplot.com/tests/data-renderers.php#highlighter_778965
IsaacSharePoint Client Side DeveloperAuthor Commented:
I know. I'm just trying to learn OOP. The best way to learn is create something
Julian HansenCommented:
Ok but what about oop are you wanting to learn?

Start by describing in words what you were trying to achieve with this code and lets take it from there.
Active Protection takes the fight to cryptojacking

While there were several headline-grabbing ransomware attacks during in 2017, another big threat started appearing at the same time that didn’t get the same coverage – illicit cryptomining.

Slick812Commented:
greetings TheInnovator, , , Using Javascript effectively take time, and many tries and errors.

If you need to learn the javascript function  to create an object instance, you may reconsider your code aproach , , you have this loop -
     for (i=0;i<=data.length; i++)
       {
      var jqPlotdata = new newTruck({

that you have a Single variable " jqPlotdata" to get ALL of the many different instances, will not work, as you can not ever access but ONE, , the last instance, once the loop ends.

if you are going to have a function for a class definition then you may as well have it do all that is needed for to get the result you need.

as in the PIE chart page I guess you need a output result as something like -
trucks = [
    ['Virginia', 112],['Maryland', 89], ['Delaware', 94],
    ['Ohio', 86],['Maine', 67]
  ]

So the purpose is to Add Up all of the associated State numbers of trucks.

There can be many many different ways to code this, I will give you some of my opinion.

I would make a function that would store and then tabulate the Pie Array in a single instance object.

I would use a   addTruck(state1, amount1)  method, that you would LOOP and give the state and number of trucks in that state, like this -
function truck2pie ( ) {
this.inputs= {};
this.states = [];


this.addTruck = function (state1, amount1){
  if (!this.inputs[state1]){
  this.states.push(state1);
  this.inputs[state1] =0;
  }
  this.inputs[state1] +=amount1;
  }
  
this.makePieArray = function (){
  var pieAry =[];
  for (i = 0; i < this.states.length; ++i) {
	pieAry.push([this.states[i] , this.inputs[this.states[i]]]);
    }
  return pieAry;
  }

} // end of function truck2pie

Open in new window


It may operate like this -

var truckPie = new truck2pie ( );
for (i=0;i<=data.length; i++)
 {  
  truckPie.addTruck(data.d.results[i].State,  data.d.results[i].numberOfTrucks);
}

Open in new window


This will not work with the code DB extract that you have because you furthur sub divide the states in to counties ( really do not understand the town inclusion), doing the states and counties will complicate the organization of the count numbers AND really complicate a single pie chart with states and counties and numbers.
but this may give you an Idea of something yo may can begin with for the info-data collection and organization,

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
IsaacSharePoint Client Side DeveloperAuthor Commented:
julianH,

What I am trying to do is get the total number of trucks for each county or state.  So in my code, I wanted to use the factory pattern as a solution to achieve my objective.  In my code above, after getting my data using rest, I was trying to create a loop as I created an instance of the class.  Obviously, this was all wrong according to 'slick812'.  I would also like to know your method using OOP.

slick812,

Thanks for your comment.  I appreciate it.  I believe seeing others approaches will really help me to grasp the concept.
I think I understand what you are doing but a bit confused.  How does the this.makePieArray() method get called?  

Also, what design pattern is that?  Any online resources that talks about it?
IsaacSharePoint Client Side DeveloperAuthor Commented:
slick812,

In your first block of code on line 17, what is the below doing?
 this.input[this.states[i]]]

Open in new window


Also, could you do this in jsfiddle  I started it but need help finishing it.
IsaacSharePoint Client Side DeveloperAuthor Commented:
Thanks Slick812.

I got your solution to work but I have a few questions about the design pattern.  I will post another question in regards to this.

Thanks again.
Slick812Commented:
Sorry, I was away from my correspondence for EE,  so I'm here now, you ask about -
      this.input[this.states[j]]


I did NOT place any explanation comments in my code, as I have absolutely no Idea what you already know about javascript, and what I may need to explain.
I stared with 2 data containers as -
     this.inputs= {};
     this.states = [];

the states array, is used as an INDEX reference storage container, , for the many state's Names, which I then use to access the Inputs Object stored numbes, as this allows me to "Sort" out the different "States" numbers, as Objects segregate the data packets, by a "name" text reference  as -
    this.inputs.Virginia
would hold the number of the added Virginia trucks.

I know in the output array for pie chart that I need the state Name and the total number, I use the FOR LOOP with the states array -
       for (j = 0; j < this.states.length; ++j) {
to get all of the states "Names", and since I have the inputs object with "Names" reference access, I use the state name in -  this.states[j] - to access the Number total in the inputs object -
     this.input[this.states[j]]
which would compute to -
     this.input["Virginia"]
for different names.


In programming operations that need to store many data sections (packets , segments), then need to sort, arrange and-or list them,  for output. You need to know exactly the required end result needed (an array of arrays in this case) so you can include storage structures in the function that you can do sorting, re-arrangement, filtering, or various listing, as you need to get your output.
 - - - - - - - - - - - - - - -

You say - "I have a few questions about the design pattern"

You originally mention this "I want to use javascript factory pattern and also prototypes", I have made many javascript operations that use what some may or may not call a "factory pattern", the use of a function Class that is modifiable in the initialization to DIFFERENT uses (Inputs, sorting, and or output) according to the Different options from a dynamic source, is one of my main programming paths. However, the Idea-definition of "factory pattern", is vastly different than doing development in actual code,  and then stretching, shoving, re-doing, re-structuring, and debugging the code work to be changeable for different dynamic options that occur and have the required output.

In this You have NO Dynamic Options (changeable), you have ONLY a single data source structuring, and a single output requirement, So I do not understand why you would even consider the idea of "factory pattern" for this operation?

I had NO THINKING at all , NONE, about a "Patten" of programming, or of a "Definition" of the way I did this code work, this is a total waste of time for a developer, I use my experience and many times previous code work, to know some arrangement of operations , storage, and loops to use, to piece together, one thing at a time and test (debug) to work towards the needed goal.
IsaacSharePoint Client Side DeveloperAuthor Commented:
Thanks Slick812

There was no real reason for considering the "factory pattern" other than to understand how, why and when to use it.  As stated initially, I am just trying to learn and understand OOP.

Thanks for the breakdown of your code.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.