CountlyHelpers

CountlyHelpers

Source:

Some helper functions to be used throughout all views. Includes custom popup, alert and confirm dialogs for the time being.

Methods

(static) addColumnSelector(dtable, config, tableName)

Source:

Adds column selector to data table

Parameters:
Name Type Description
dtable object

data table jquery object

config object

configuration for disabling columns

Properties
Name Type Description
disabled object

object for disabled column names. Optional. If nothing set, you can disable all columns. Example: {"name1":true,"name2":true}

visible object

Default visible columns. If none set - first N are taken to not exceed max column count. If user has changed it, it gets overwritten by data stored in local storage.

maxCol number

max column count. If not set - max == all columns.

tableName string

table name. Used to create name for storage. need to be unique for every table.

Example: CountlyHelpers.addColumnSelector(dtable,{"disabled:"{"name1":true,"name2":true},maxCol:6},"myTableName"); Safe way would be adding in "fnInitComplete" function:

"fnInitComplete": function(oSettings, json) { $.fn.dataTable.defaults.fnInitComplete(oSettings, json); CountlyHelpers.addColumnSelector(this, {"disabled":{"name1":true,"name2":true}, "maxCol":5 }, "viewsTable"); },

(static) alert(msg, type, moreData)

Source:

Display modal alert popup for quick short messages that require immediate user's attention, as error submitting form

Example
CountlyHelpers.alert("Some error happened", "red");
Parameters:
Name Type Description
msg string

message to display in alert popup

type string

type of alert red for errors and green for success

moreData object

more data to display

Properties
Name Type Description
image string

image id

title string

alert title

(static) appIdsToNames(context) → {string}

Source:

Convert array of app ids to comma separate string of app names

Example
//outputs Test1, Test2, Test3
CountlyHelpers.appIdsToNames(["586e3216326a8b0a07b8d87f", "586e339a326a8b0a07b8ecb9", "586e3343c32cb30a01558cc3"]);
Parameters:
Name Type Description
context array

array with app ids

Returns:

list of app names (appname1, appname2)

Type
string

(static) changeDialogHeight(dialog, animate)

Source:

If contents of the popup change, you may want to resice the popup

Example
var dialog = $("#cly-popup").clone().removeAttr("id").addClass('campaign-create');
CountlyHelpers.revealDialog(dialog);
//when content changes
CountlyHelpers.changeDialogHeight(dialog, true)
Parameters:
Name Type Description
dialog jquery_object

jQuery dialog reference

animate boolean

should resizing be animated

(static) changeDTableColVis(config, dtable, tableName, col, visible) → {boolean}

Source:

function hides column in data table and stores config in local storage

Parameters:
Name Type Description
config object

config object for table

dtable object

data table object

tableName string

name to use to save in local storage settings

col number

column number

visible boolean

true - if need to show

Returns:

if changes were applied - true, if not false. Changes could not be applied if selecting this column means selecting more columns than allowed

Type
boolean

(static) clip(fopt, nothingopt) → {function}

Source:

Creates function to be used as mRender for datatables to clip long values

Parameters:
Name Type Attributes Description
f function <optional>

optional function to change passed data to render and return changed object

nothing string <optional>

text to display in cellS

Returns:

to be used as mRender for datatables to clip long values

Type
function

(static) closeRows(dTable)

Source:

Close all opened datatables rows

Example
CountlyHelpers.closeRows(self.dtable);
Parameters:
Name Type Description
dTable object

jQuery object datatable reference

(static) confirm(msg, type, callback, buttonTextopt, moreData)

Source:

Display modal popup that requires confirmation input from user

Example
CountlyHelpers.confirm("Are you sure?", "red", function (result) {
   if (!result) {
       //user did not confirm, just exit
       return true;
   }
   //user confirmed, do what you need to do
});
Parameters:
Name Type Attributes Description
msg string

message to display in alert popup

type string

type of alert red for errors and green for success

callback function

to determine result of the input

buttonText array <optional>

[0] element for cancle button text and [1] element for confirm button text

moreData object

more data to display

Properties
Name Type Description
image string

image id

title string

alert title

(static) confirmWithCheckbox(msg, type, hasCheckbox, checkboxTitle, callback, buttonTextopt)

Source:

Display modal popup that requires confirmation input from user and optional checkbox

Example
CountlyHelpers.confirmWithCheckbox("Are you sure?", "red", true, "Chechbox label text", function (result) {
   if (!result) {
       //user did not confirm, just exit
       return true;
   }
   //user confirmed, do what you need to do
});
Parameters:
Name Type Attributes Description
msg string

message to display in alert popup

type string

type of alert red for errors and green for success

hasCheckbox boolean

popup has checkbox? or not.

checkboxTitle string

title of checkbox element

callback function

to determine result of the input

buttonText array <optional>

[0] element for cancle button text and [1] element for confirm button text

(static) createDrawer(options) → {object}

Source:

Create drawer

Example
var drawer = CountlyHelpers.createDrawer({
          id: "my-id",
          form: $('#id-of-elem'), //if using form
          title: 'My Drawer title',
          applyChangeTriggers: true, //add triggers
          onUpdate: function(){
             //check all fields here
           },
           resetForm: function() {
               //empty all fields. Text fields are emptied automatically because options.preventBaseReset is not set.
           },
           onClose: function(callback) {
               callback(true); //allow closing form
               callback(false); //don't close form
           },
           onClosed: function() {
               //form is closed
           }
       });
//After creation drawer object is returned. Object has multiple functions:
drawer.open() //opens drawer
drawer.close(force); //closes drawer. force - close anyway even if there is onClose function set. (Withot validating)
drawer.resetForm(); //resets drawer (Normally called after closing or before opening drawer)
   
Parameters:
Name Type Description
options object

Options object

Properties
Name Type Description
id string

Optional. Id for drawer

template object

Handelbars template object(optional). After creating element from template ".details" and ".buttons" are moved to drawer object. Other parts are not used.

templateData object

Data for template (optional)

form object

(optional) Existing html element with form. ".details" and ".buttons" are moved to drawer object. Options.form element is removed.

title string

(optional) Title for drawer

root object

(optional) Element to which drawer should be appended. If not set drawer is appended to (".widget").

saveButtonText boolean

(optional) If there is only single button and there is not set any button using form or template - then passing this string sets text for save button.

preventBaseReset boolean

(optional) If true then when reseting form base reset function,which empties text fields won't be called.

applyChangeTriggers object

(optional) If true - Ads event listeners on textaria and input[text], cly-multi-select, cly-single select in form to trigger "cly-drawer-form-updated" on drawer. * This event callls options.onUpdate function.

onUpdate function

(optional) function called when "cly-drawer-form-updated" is triggered on drawer.

onClose(callback) function

(optional) function called when calling drawer.close() or hitting [X] button. Has one parameter - callback function. Only if callback function returns true as first param - drawer is closed.

onClosed(callback) function

(optional) function called after drawer is successfully closed.

Returns:

Drawer object

Type
object

(static) createMetricModel(countlyMetric, metric, $, fetchValueopt)

Source:

Create Countly metric model to fetch metric data from server and provide it to views

Example
window.countlyDensity = {};
  countlyDensity.checkOS = function(os, density){
       var lastIndex = density.toUpperCase().lastIndexOf("DPI");
       if(os.toLowerCase() == "android" && lastIndex !== -1 && lastIndex === density.length - 3)
           return true;
       if(os.toLowerCase() == "ios" && density[0] == "@")
           return true;
       return false;
  };
  CountlyHelpers.createMetricModel(window.countlyDensity, {name: "density", estOverrideMetric: "densities"}, jQuery, function(val, data, separate){
       if(separate){
           //request separated/unprocessed data
           return val;
       }
       else{
           //we can preprocess data and group, for example, by first letter
           return val[0];
       }
  });
Parameters:
Name Type Attributes Description
countlyMetric object

initial metric object if you want to pre provide some methods, etc

metric string

metric name to retrieve from server

$ jquery

local jquery reference

fetchValue function <optional>

default function to fetch and transform if needed value from standard metric model

(static) expandRows(dTable, getData, context)

Source:

In some cases you may want to allow expanding rows of your datatable. To do that you must add unique id to each row via datatables fnRowCallback property

Example
function formatData(data){
   // `data` is the original data object for the row
   //return string to display in subcell
   var str = '';
	if(data){
		str += '<div class="datatablesubrow">'+
       JSON.stringify(data)+
       '</div>';
   }
   return str;
}
this.dtable = $('.d-table').dataTable($.extend({}, $.fn.dataTable.defaults, {
     "aaData": crashData.data,
		"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
			$(nRow).attr("id", aData._id);
		},
     "aoColumns": [
			{ "mData": "ts"}, "sType":"format-ago", "sTitle": jQuery.i18n.map["crashes.crashed"]},
			{ "mData": "os", "sType":"string", "sTitle": jQuery.i18n.map["crashes.os_version"] },
			{ "mData": "device"}, "sType":"string", "sTitle": jQuery.i18n.map["crashes.device"]},
			{ "mData": "app_version", "sType":"string", "sTitle": jQuery.i18n.map["crashes.app_version"] }
     ]
 }));
 CountlyHelpers.expandRows(this.dtable, formatData);
Parameters:
Name Type Description
dTable object

jQuery object datatable reference

getData function

callback function to be called when clicking ont he row. This function will receive original row data object you passed to data tables and should return HTML string to display in subcell

context object

this context if needed, which will be passed to getData function as second parameter

(static) export(count, data, asDialog, exportByAPI, instance) → {object}

Source:

Displays database export dialog

Example
var dialog = CountlyHelpers.export(300000);
//later when done
CountlyHelpers.removeDialog(dialog);
Parameters:
Name Type Description
count number

total count of documents to export

data object

data for export query to use when constructing url

asDialog boolean

open it as dialog

exportByAPI boolean

export from api request, export from db when set to false

instance boolean

optional. Reference to table to get correct colum names(only if there is need to select columns to export) There must be changes made in table settings to allow it. (table.addColumnExportSelector = true and each column must have columnsSelectorIndex value as field in db)

Returns:

jQuery object reference to dialog

Type
object

(static) generatePassword(length, no_special) → {string}

Source:

Generate random password

Example
//outputs 4UBHvRBG1v
CountlyHelpers.generatePassword(10, true);
Parameters:
Name Type Description
length number

length of the password

no_special boolean

do not include special characters

Returns:

password

Type
string

(static) initBreadcrumbs(breadcrumbs, el)

Source:

Function to add breadcrumbs

Parameters:
Name Type Description
breadcrumbs Array

Array of links with name and url

el DOMELement

This is the element to which the breadcrumb will be prepended to in the beginning

(static) initializeMultiSelect(element)

Source:

Initialize countly dropdown multi select. In most cases it is done automatically, only in some cases, when content loaded via ajax request outside of view lifecycle, you may need to initialize it yourself for your content specifically

Example
CountlyHelpers.initializeMultiSelect($("#my-dynamic-div"));
Parameters:
Name Type Description
element object

jQuery object reference

(static) initializeSelect(element)

Source:

Initialize countly dropdown select. In most cases it is done automatically, only in some cases, when content loaded via ajax request outside of view lifecycle, you may need to initialize it yourself for your content specifically

Example
CountlyHelpers.initializeSelect($("#my-dynamic-div"));
Parameters:
Name Type Description
element object

jQuery object reference

(static) initializeTableOptions(element)

Source:

Initialize dropdown options list usually used on datatables. Firstly you need to add list with class 'cly-button-menu' to your template or add it in the view. Additionally you can add class dark to use dark theme. After that datatables last column for options should return a element with cly-list-options class and should have cell classes shrink and right and should not be sortable Then call this method in your view and you can start listening to events like: cly-list.click - when your cly-list-options element is clicked, passing click event as data cly-list.open - when list is opened, passing click event as data cly-list.close - when list is closed, passing click event as data cly-list.item - when item is clicked, passing click event as data

Examples

Adding list to HTML template

<div class="cly-button-menu dark cohorts-menu" tabindex="1">
    <a class="item delete-cohort" data-localize='common.delete'></a>
    <a class="item view-cohort" data-localize='cohorts.view-users'></a>
</div>

Creating last column in datatables

{ "mData": function(row, type){
    return '<a class="cly-list-options"></a>';
}, "sType":"string", "sTitle": "", "sClass":"shrink center", bSortable: false  }

Listening to events

$(".cly-button-menu").on("cly-list.click", function(event, data){
    var id = $(data.target).parents("tr").data("id");
});
Parameters:
Name Type Description
element object

jQuery object reference for container

(static) initializeTextSelect(element)

Source:

Initialize countly text select. In most cases it is done automatically, only in some cases, when content loaded via ajax request outside of view lifecycle, you may need to initialize it yourself for your content specifically

Example
CountlyHelpers.initializeTextSelect($("#my-dynamic-div"));
Parameters:
Name Type Description
element object

jQuery object reference

(static) isJSON(val) → {boolean}

Source:

Check the value which passing as parameter isJSON or not return result as boolean

Example
CountlyHelpers.isJSON(variable);
Parameters:
Name Type Description
val object

value of form data

Returns:

is this a json object?

Type
boolean

(static) loadCSS(css, callbackopt)

Source:

Load CSS file

Example
CountlyHelpers.loadCSS("/myplugin/stylesheets/custom.css");
Parameters:
Name Type Attributes Description
css string

path or url to css file

callback callback <optional>

callback when file loaded

(static) loading(msg) → {object}

Source:

Displays loading icong and returns reference to dialog so you could close it once loading is done

Example
var dialog = CountlyHelpers.loading("we are doing something");
//later when done
CountlyHelpers.removeDialog(dialog);
Parameters:
Name Type Description
msg string

message to display in loading popup

Returns:

jQuery object reference to dialog

Type
object

(static) loadJS(js, callbackopt)

Source:

Load JS file

Example
CountlyHelpers.loadJS("/myplugin/javascripts/custom.js");
Parameters:
Name Type Attributes Description
js string

path or url to js file

callback callback <optional>

callback when file loaded

(static) model()

Source:

Create new model

(static) newJSONEditor(json, typeopt, callbackopt)

Source:

Create new model

Parameters:
Name Type Attributes Description
json object

json object

type string <optional>

classname

callback function <optional>

callback function

(static) notify(msg)

Source:

Display dashboard notification using Amaran JS library

Example
CountlyHelpers.notify({
   title: "This is title",
   message: "Main message text",
   info: "Additional info"
});
Parameters:
Name Type Description
msg object

notification message object

Properties
Name Type Attributes Default Description
title string <optional>

title of the notification

message string <optional>

main notification text

info string <optional>

some additional information to display in notification

delay number <optional>
10000

delay time in miliseconds before displaying notification

type string <optional>
ok

message type, accepted values ok, error and warning

position string <optional>
top right

message position

sticky string <optional>
false

should message stick until closed

clearAll string <optional>
false

clear all previous notifications upon showing this one

closeOnClick string <optional>
false

should notification be automatically closed when clicked on

onClick function <optional>

on click listener

(static) openResource(url)

Source:

Display modal popup with external resource from provided URL in iframe. Make sure to use https version of resource for it to work on both http and https dashboard

Example
CountlyHelpers.openResource("http://resources.count.ly/docs");
Parameters:
Name Type Description
url string

full absolute url to external resource to display in popup

(static) parseAndShowMsg(msg) → {boolean}

Source:

Legacy method for displaying notifications. User CountlyHelpers.notify instead

Parameters:
Name Type Description
msg string

msg to display

Returns:

true - if message is not defined, else returns nothing

Type
boolean

(static) popup(element, custClassopt, isHTMLopt)

Source:

Display modal popup UI

Example
CountlyHelpers.popup("<h1>Hello</h1>", "red", true);
Parameters:
Name Type Attributes Description
element string | object

if third parameter isHTML is true, then HTML code as string is expected, else element's selector or element itself is expected and it's HTML contents will be copied into popup

custClass string <optional>

add custom css class to dialog for easier manipulation

isHTML boolean <optional>

changes the behavior of first parameter element

(static) refreshTable(dTable, newDataArr)

Source:

Refresh existing datatable instance on view refresh, providing new data

Example
CountlyHelpers.refreshTable(self.dtable, data);
Parameters:
Name Type Description
dTable object

jQuery object datatable reference

newDataArr object

array with new data in same format as provided while initializing table

(static) removeDialog(dialog)

Source:

Remove existing dialog

Example
var dialog = $("#cly-popup").clone().removeAttr("id").addClass('campaign-create');
CountlyHelpers.revealDialog(dialog);
//when dialog not needed anymore
CountlyHelpers.removeDialog(dialog);
Parameters:
Name Type Description
dialog jquery_object

jQuery dialog reference

(static) reopenRows(dTable, getData, context)

Source:

If you allow to open/expand rows, then when refreshing table they will close again. To avoid that you must call this function on each refresh after calling CountlyHelpers.refreshTable

Example
CountlyHelpers.refreshTable(self.dtable, data);
CountlyHelpers.reopenRows(self.dtable, formatData);
Parameters:
Name Type Description
dTable object

jQuery object datatable reference

getData function

callback function to be called when clicking ont he row. This function will receive original row data object you passed to data tables and should return HTML string to display in subcell

context object

this context if needed, which will be passed to getData function as second parameter

(static) revealDialog(dialog)

Source:

Instead of creating dialog object you can use this method and directly pass jquery element to be used as dialog content, which means complete customization

Example
var dialog = $("#cly-popup").clone().removeAttr("id").addClass('campaign-create');
CountlyHelpers.revealDialog(dialog);
Parameters:
Name Type Description
dialog jquery_object

jQuery object unnattached, like cloned existing object

(static) tableExport(dtable, data, asDialog, oSettings) → {object}

Source:

Displays raw data table export dialog

Example
var dialog = CountlyHelpers.export(300000);
//later when done
CountlyHelpers.removeDialog(dialog);
Parameters:
Name Type Description
dtable opject

data

data object

data for export query to use when constructing url

asDialog boolean

open it as dialog

oSettings object

oSettings object of the dataTable

Returns:

jQuery object reference to dialog

Type
object

(static) upload(el, url, data, callback)

Source:

Upload file by the passed optional parameters

Parameters:
Name Type Description
el object

dom element

url string

upload url

data object

data object that will send with upload request

callback function

callback for upload result

(static) validateEmail(email) → {boolean}

Source:

Validate email address

Example
//outputs true
CountlyHelpers.validateEmail("test@test.test");

//outputs false
CountlyHelpers.validateEmail("test@test");
Parameters:
Name Type Description
email string

email address to validate

Returns:

true if valid and false if invalid

Type
boolean

(static) validatePassword(password) → {boolean}

Source:

Validate password based on settings provided via security configuration

Parameters:
Name Type Description
password string

password to validate

Returns:

true if valid and false if invalid

Type
boolean