GB JavaScript API

Querys

finstack.eval

Be able to call an eval op on server. Typically this functionality should be used with a promise. See an example below

This is how we do this
finstack.eval('readAll(site)') 


or 


finstack.eval('read(site).finWeatherData()')

finstack.evalAll 

To create an event/ program that runs when a graphic is started you will need to have the variable be linked to a custom event, and set the event name to be on start. 

This is how we do this
var foo = this.value;
fooBat 	= this.value * 8;

DId you know you could do this

You don't have to use a eval or evalAll in the program, you could just create a virtualPoint query instead.

finFilteredFuncEval

Let's say you had 3 functions, and they all returned a list of people. Let's say there were females and males in there too. If you add a tag to your 3 functions called person, then your function could look like this.

finFilteredFuncEval(person,female and age < 24)

also if any of those records have a order tag on them the output will automatically be ordered.

This is basically a function that allows you to call other functions and add the outputs together. This was done in fan, so it's not slow like axon.

finGraphicRemoteAssets 

right-click Resources > Add Remote will call finRemoteAsset()
finRemoteAsset() will look for all functions with marker "finRemoteAsset" and concat the result of their execution.
When user select one of the values, it will create a record type remoteAsset or style (if resource is css file) or script (if resource is js).
The project needs to be saved and reloaded to see the resource loaded. This is a bug of Rochelle.
examples can be found in finGraphicsResource  pod

name: finGraphicRemoteAssets
func
finRemoteAsset
construct: "finGraphicRemoteAssets()"
src:

  () => do
        [
            {dis:"Allow Commanding",value:`/finPod/finGraphicResourcesExt/res/elements/allowCommandingProgram.json`},
            {dis:"Component Statusg",value:`/finPod/finGraphicResourcesExt/res/elements/componentStatusProgram.json`},
            {dis:"Degrade Behavior",value:`/finPod/finGraphicResourcesExt/res/elements/degradedProgram.json`},
            {dis:"Duct Component Program",value:`/finPod/finGraphicResourcesExt/res/elements/ductComponentProgram.json`},
            {dis:"Floorplan Polygon Program",value:`/finPod/finGraphicResourcesExt/res/elements/floorplanPolygonProgram.json`},
            {dis:"Related Bubbles",value:`/finPod/finGraphicResourcesExt/res/elements/relatedBubblesProgram.json`},
            {dis:"Query Update Program",value:`/finPod/finGraphicResourcesExt/res/elements/siteTemplatePrograms.json`},
            {dis:"Open MagicBubbles Program",value:`/finPod/finGraphicResourcesExt/res/elements/openMagicBubblesProgram.json`},
        ]
    end


Language Translator 

This will translate languages in the graphics builder:

var labelTxt = getByName('foo');
labelTxt.value = window.languageManager["s1SharedSat"];


finJSLibraries 

name: finJSLibraries
func
finRemoteAsset
src:

 () => do
        [
            {dis:"Lodash 4",value:`/finPod/finGraphicResourcesExt/res/jslibs/lodash.min.js`}
        ]
    end


Console.log your eval 

This is how you could use the console, and return data from a query.

var foo = finstack.eval('read(site).finWeatherData()')
 
foo.then(function(data){console.log(data.result.toObj());})

The result will look like this:

[{"cur_temp":66,"cur_tempUnit":"°F","cur_time":"09:37:00","forecast":[{"date":"11/16/16","tempMax":65,"tempMaxUnit":"°F","sunrise":"06:24:00","iconText":"Slight Showers","sunset":"16:47:00","icon":"wi-sprinkle","cond":4,"tempMin":52,"tempMinUnit":"°F"},{"date":"11/17/16","tempMax":73,"tempMaxUnit":"°F","sunrise":"06:25:00","iconText":"Clear Sky","sunset":"16:47:00","icon":"wi-day-sunny","cond":1,"tempMin":52,"tempMinUnit":"°F"},{"date":"11/18/16","tempMax":75,"tempMaxUnit":"°F","sunrise":"06:26:00","iconText":"Clear Sky","sunset":"16:46:00","icon":"wi-day-sunny","cond":1,"tempMin":50,"tempMinUnit":"°F"}],"cur_cond":2}]




Find Things


query()

The query function uses a haystack filter to find the 1st record inside the graphics app.

This is how we do this
var myComponent = query('foo and component');

queryAll()

queryAll() uses a haystack filter and returns all the matching records

This is how we do this
var myComponent = queryAll('foo and component and area==12');


//returns all components that have the foo tag and has an area tag that = 12


finFindRef() 

 finFindRefs makes a structure for you so you can get all the tags from all of it's refs. Once the finFinRef is used, you can simply use .navName after your var to trap the specified ref's tags.

This is how we do this
read(point).finFindRefs()->floorRefObj->dis

The 2nd parameter can be 2. This would allow you to get all of it's refs, and all of it's refs. For things like let's say the site had a ref to something else

This is how we do this
read(point).finFindRefs(2)->siteRefObj->weatherRefObj


getPath

getPath is typically used inside of a model. Let's say I have a model, and in the model I have 2 labels called label1, and label2. getPath will let you get the record based on the name. This can be nested as well.

This is how we do this
// Get Child Views
var valueLabel      = getPath("valueGroup.valueLabel");
var statusIndicator = getPath("valueGroup.statusIndicator");
var pointName       = getPath("nameGroup.nameLabel");




Virtual Points


refreshPoints

To create an event/ program that runs when a graphic is started you will need to have the variable be linked to a custom event, and set the event name to be on start. 

This is how we do this
var myQuery = query(virtualPoint and sensor);


refreshPoints(myQuery);


External Libraries

moment.js

Moment.js  is a library that is available for you to use. It's an open source project, that allows you to Parse, validate, manipulate, and display dates in JavaScript. It allows you to make a date and time look pretty. See examples below.

This is how we do this
moment().format('MMMM Do YYYY, h:mm:ss a'); // November 4th 2016, 11:26:49 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY");               // Nov 4th 16
moment().format('YYYY [escaped] YYYY');     // 2016 escaped 2016
moment().format();                          // 2016-11-04T23:26:49-07:00

http://momentjs.com/docs/


numeral.js

Numeral.js  is a library that is available for you to use. It's an open source project, that allows you to format and manipulate numbers. See some examples below

This is how we do this
var string = numeral(1000).format('0,0');
// '1,000'

http://numeraljs.com/


JavaScript 

arrays

In the graphics builder it's pure javaScript , which means you can work with arrays and use all the standard array functions that are in javSCript. Make sure before using a function that you check to see which browsers it is avaialble in . The below example shows how you can make an array. 

This is how we do this
var fruits = ["Apple", "Banana"];

console.log(fruits.length);
// 2
                      
This is how we do this
var first = fruits[0];
// Apple

var last = fruits[fruits.length - 1];
// Banana
                      

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array



object

An object is a list of key value pairs. See below example

This is how we do this
var foo 		= {age:12,lastName:"Bryant",firstName:"Kobe"}
myLabel.value	= foo.lastName 


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object



number

The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Numberobject is created using the Number() constructor.

This is how we do this
var foo = 12 
myLabel = foo * 12


Number.isFinite()
Number.isInteger()
Number.isNaN()
Number.isSafeInteger()
Number.parseFloat()
Number.parseInt()
Number.prototype.toExponential()
Number.prototype.toFixed()
Number.prototype.toLocaleString()
Number.prototype.toPrecision()
Number.prototype.toSource()
Number.prototype.toString()
Number.prototype.valueOf()                      


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number



math

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

This is how we do this
var roomTemp = query('virtualPoint and zone and temp and sensor');
var setpoint = query('virtualPoint and zone and temp and sp');


myLabel.value = Math.max([roomTemp.curVal,setpoint.curval])

             
  • Math.abs(x)
    • Returns the absolute value of a number.
  • Math.acos(x)
    • Returns the arccosine of a number.
  • Math.acosh(x)
    • Returns the hyperbolic arccosine of a number.
  • Math.asin(x)
    • Returns the arcsine of a number.
  • Math.asinh(x)
    • Returns the hyperbolic arcsine of a number.
  • Math.atan(x)
    • Returns the arctangent of a number.
  • Math.atanh(x)
    • Returns the hyperbolic arctangent of a number.
  • Math.atan2(y, x)
    • Returns the arctangent of the quotient of its arguments.
  • Math.cbrt(x)
    • Returns the cube root of a number.
  • Math.ceil(x)
    • Returns the smallest integer greater than or equal to a number.
  • Math.clz32(x)
    • Returns the number of leading zeroes of a 32-bit integer.
  • Math.cos(x)
    • Returns the cosine of a number.
  • Math.cosh(x)
    • Returns the hyperbolic cosine of a number.
  • Math.exp(x)
    • Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
  • Math.expm1(x)
    • Returns subtracting 1 from exp(x).
  • Math.floor(x)
    • Returns the largest integer less than or equal to a number.
  • Math.fround(x)
    • Returns the nearest single precision float representation of a number.
  • Math.hypot([x[, y[, …]]])
    • Returns the square root of the sum of squares of its arguments.
  • Math.imul(x, y)
    • Returns the result of a 32-bit integer multiplication.
  • Math.log(x)
    • Returns the natural logarithm (loge, also ln) of a number.
  • Math.log1p(x)
    • Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
  • Math.log10(x)
    • Returns the base 10 logarithm of a number.
  • Math.log2(x)
    • Returns the base 2 logarithm of a number.
  • Math.max([x[, y[, …]]])
    • Returns the largest of zero or more numbers.
  • Math.min([x[, y[, …]]])
    • Returns the smallest of zero or more numbers.
  • Math.pow(x, y)
    • Returns base to the exponent power, that is, baseexponent.
  • Math.random()
    • Returns a pseudo-random number between 0 and 1.
  • Math.round(x)
    • Returns the value of a number rounded to the nearest integer.
  • Math.sign(x)
    • Returns the sign of the x, indicating whether x is positive, negative or zero.
  • Math.sin(x)
    • Returns the sine of a number.
  • Math.sinh(x)
    • Returns the hyperbolic sine of a number.
  • Math.sqrt(x)
    • Returns the positive square root of a number.
  • Math.tan(x)
    • Returns the tangent of a number.
  • Math.tanh(x)
    • Returns the hyperbolic tangent of a number.
  • Math.toSource()
    • Returns the string "Math".
  • Math.trunc(x)
    • Returns the integral part of the number x, removing any fractional digits.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math



statements and declaritations

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

This is how we do this
//// if else
if (x > 5) {

} else if (x > 50) {

} else {

}


/// Switch
var foo = 0;
switch (foo) {
  case -1:
    console.log('negative 1');
    break;
  case 0: // foo is 0 so criteria met here so this block will run
    console.log(0);
    // NOTE: the forgotten break would have been here
  case 1: // no break statement in 'case 0:' so this case will run as well
    console.log(1);
    break; // it encounters this break so will not continue into 'case 2:'
  case 2:
    console.log(2);
    break;
  default:
    console.log('default');
}


/// for of
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements



Conditional (ternary) Operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

This is how we do this
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";


var stop = false, age = 23;

age > 18 ? (
    alert("OK, you can go."),
    location.assign("continue.html")
) : (
    stop = true,
    alert("Sorry, you are much too young!")
);


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements


Interpolate

Interpolate will look at a string, and if it has a $ in it, it will then look at an object for that key, and replace the value with it.  

Example:

Let's say you navigate to AHU-21 in teh database and you are open to a graphic. If you use interpolate("$navName $id"), then it will replace $navName and $id with the tag values from that AHU-21. 


Commonly Used 

Reduce-Arrays

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments:

  • previousValue
  • currentValue
  • currentIndex
  • array

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Note: If initialValue isn't provided, reduce will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.



var foo = query('foo');

///The below reduce function allows you to find the object that has the min value for age. 

var minCallback = function(a, b)
{
    return a.age <= b.age ? a : b;
};

foo.value = [{name:"jason",age:5},{name:"Minh",age:10},{name:"Minh",age:15}].reduce(minCallback).age;
// console.log([{name:"jason",age:5},{name:"Minh",age:10},{name:"Minh",age:15}].reduce(minCallback))

var minCallback = function(prevValue, curValue, curIndex,array)
{
    if(prevValue.age<= curValue.age)
        return prevValue;

    return curValue;//return entire object
}
var person  = [{name:"jason",age:12},{name:"Minh" ,age:9}].reduce(minCallback);

console.log(person)


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce



Map-Arrays

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the thisseen by a function.

map does not mutate the array on which it is called (although callback, if invoked, may do so).

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited.


var foo = query('foo');

var jason = [1, 2, 3, 4].map (function(item){
    return item * 2;

});

foo.value = jason;
Need an example of using a map, and inside that using the query to do somthing.


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map



filter-Arrays

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to truecallback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

If a thisArg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value.  Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the thisseen by a function.

filter() does not mutate the array on which it is called.

The range of elements processed by filter() is set before the first invocation of callback. Elements which are appended to the array after the call to filter() begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time filter() visits them; elements that are deleted are not visited.



var foo = query('foo');

var jason = [1, 2, 3, 4].filter(function(item){
    return item > 2;
});

foo.value = jason;


/// This will return 3,4
var foo = query('foo');

var jason = [{name:"jason",age:12},{name:"Minh" ,age:9},{name:"Test" ,age:99}].filter(function(item){
    return item.age > 10;
});

console.log(jason);


//// This will return [{name:"jason",age:12},{name:"Test" ,age:99}]


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter



some-Arrays

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns falsecallback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed.

If a thisArg parameter is provided to some(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the thisseen by a function.

some() does not mutate the array on which it is called.

The range of elements processed by some() is set before the first invocation of callback. Elements that are appended to the array after the call to some() begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that some() visits that element's index; elements that are deleted are not visited.




var foo = query('foo');

//// Checks to see if some of the items in the array match the condition. Below case it's saying are some of them numbers.

var jason = ["fooBag",1,2,3,3,45,5].some(function(item){
    return !isNaN(item)
})

foo.value = jason;


//// This will return true
var foo = query('foo');

//// Checks to see if any of the items in the array match it's condition

var jason = [{name:"jason",age:12},{name:"Minh" ,age:9},{name:"Test" ,age:99}].some(function(item){
    return item.age > 0
})

foo.value = jason;

// This will return true



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some



every-Arrays

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return truecallback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to every, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the thisseen by a function.

every does not mutate the array on which it is called.





var foo = query('foo');

/// This will return false if one of the items in the array doesn't match the condition

var jason = [{dis:"site1",area:123},{dis:"site2"}].every(function(item){
   //// return "area" in item /// This also works
   return item.hasOwnProperty("area")
})

foo.value = jason;


/// This returns false cause there is the area tag in every object
function isBigEnough(element, index, array) { 
  return element >= 10; 
} 

[12, 5, 8, 130, 44].every(isBigEnough);   // false 
[12, 54, 18, 130, 44].every(isBigEnough); // true



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every