### JavaScript Example: Transforming Data with DataPipe
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This example demonstrates how to use a DataPipe to transform items from an `appDS` DataSet into a `visDS` DataSet, mapping application-specific properties to Vis.js-specific properties. It shows the basic `map` operation and how to start the pipe to apply transformations.
```javascript
const appDS = new DataSet([
/* some app data */
]);
const visDS = new DataSet();
const pipe = createNewDataPipeFrom(appDS)
// All items can be arbitrarily transformed.
.map((item) => ({
id: item.id,
label: item.visLabel,
color: item.visColor,
x: item.visX,
y: item.visY
}))
// This builds and returns the pipe from appDS to visDS.
.to(visDS);
pipe.all().start();
// All items were transformed and piped into visDS and all later changes
// will be transformed and piped as well.
```
--------------------------------
### Add Multiple Items to vis.DataSet with Various Date Formats
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This code demonstrates adding multiple items to a vis.DataSet using the 'add' method. It showcases different ways to specify the 'start' date, including Date objects, numeric timestamps, ISO strings, and custom formats.
```JavaScript
dataset.add([
{ id: 1, content: "item 1", start: new Date() },
{ id: 2, content: "item 2", start: new Date().valueOf() },
{ id: "3", content: "item 3", start: new Date().toISOString() },
{ id: 4, content: "item 4", start: "/Date(1198908717056)/" },
{ id: 5, content: "item 5", start: undefined },
{ content: "item 6", start: new Date() }
]);
```
--------------------------------
### DataView Instance Methods API
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Lists and describes the methods available on a `vis.DataView` instance, including `get`, `getDataSet`, `getIds`, `off`, `on`, and `refresh`, along with their return types and brief explanations. Includes an example for `refresh()`.
```APIDOC
Methods:
get([options] [, data])
get(id [,options] [, data])
get(ids [, options] [, data])
Return Type: Object | Array
Description: Get a single item, multiple items, or all items from the DataView. Returns null for single item not found, empty Array for multiple IDs not found.
getDataSet()
Return Type: DataSet
Description: Get the DataSet to which the DataView is connected.
getIds([options])
Return Type: Number[]
Description: Get ids of all items or of a filtered set of items. Options 'fields' and 'type' are not applicable.
off(event, callback)
Return Type: none
Description: Unsubscribe from an event, remove an event listener.
on(event, callback)
Return Type: none
Description: Subscribe to an event, add an event listener.
refresh()
Return Type: none
Description: Refresh the filter results of a DataView. Useful when the filter function contains dynamic properties.
Example:
var data = new vis.DataSet(...);
var view = new vis.DataView(data, {
filter: function (item) {
return item.value > threshold;
}
});
```
--------------------------------
### JavaScript: Format and Filter DataSet Items
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
This example demonstrates how to create a DataSet, add items, and then retrieve formatted items using the `get` method with `fields` and `type` options. It shows how to select specific fields and convert their data types.
```javascript
// create a DataSet
var data = new vis.DataSet();
data.add([
{id: 1, text: 'item 1', date: '2013-06-20', group: 1, first: true},
{id: 2, text: 'item 2', date: '2013-06-23', group: 2},
{id: 3, text: 'item 3', date: '2013-06-25', group: 2},
{id: 4, text: 'item 4'}
]);
// retrieve formatted items
var items = data.get({
fields: ['id', 'date', 'group'], // output the specified fields only
type: {
date: 'Date', // convert the date fields to Date objects
group: 'String' // convert the group fields to Strings
}
});
```
--------------------------------
### Initialize Google Analytics Tracking
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This snippet sets up Google Analytics tracking on a web page. It loads the analytics script, creates a tracker with a specified ID, and sends a pageview hit.
```JavaScript
(function (i, s, o, g, r, a, m) { i["GoogleAnalyticsObject"] = r; (i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments); }), (i[r].l = 1 * new Date()); (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]); a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })( window, document, "script", "//www.google-analytics.com/analytics.js", "ga" );
ga("create", "UA-61231638-1", "auto");
ga("send", "pageview");
```
--------------------------------
### JavaScript vis.js DataSet Basic Operations
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
This example demonstrates the fundamental usage of `vis.DataSet`, including its creation, adding diverse data items, subscribing to all data changes, updating an existing item, removing an item, and retrieving data using various methods like `getIds`, `get`, and filtered/formatted `get`.
```javascript
// create a DataSet
var options = {};
var data = new vis.DataSet(options);
// add items
// note that the data items can contain different properties and data formats
data.add([
{id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
{id: 2, text: 'item 2', date: '2013-06-23', group: 2},
{id: 3, text: 'item 3', date: '2013-06-25', group: 2},
{id: 4, text: 'item 4'}
]);
// subscribe to any change in the DataSet
data.on('*', function (event, properties, senderId) {
console.log('event', event, properties);
});
// update an existing item
data.updateOnly({id: 2, group: 1});
// remove an item
data.remove(4);
// get all ids
var ids = data.getIds();
console.log('ids', ids);
// get a specific item
var item1 = data.get(1);
console.log('item1', item1);
// retrieve a filtered subset of the data
var items = data.get({
filter: function (item) {
return item.group == 1;
}
});
console.log('filtered items', items);
// retrieve formatted items
var items = data.get({
fields: ['id', 'date'],
type: {
date: 'ISODate'
}
});
console.log('formatted items', items);
```
--------------------------------
### Initialize vis.DataSet with Custom Field ID and Type Conversion
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This code initializes a new vis.DataSet instance. It configures 'id' as the primary key field and sets up a conversion rule to parse 'start' property values into Date objects.
```JavaScript
var dataset = new vis.DataSet({
fieldId: "id",
convert: {
start: "Date"
}
});
```
--------------------------------
### JavaScript DataView Usage Example
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Demonstrates how to create a DataSet, apply a DataView with filtering and field selection, subscribe to DataView changes, and update data to observe view reactions. It also shows how to retrieve IDs and items from the filtered view.
```JavaScript
// create a DataSet
var data = new vis.DataSet();
data.add([
{id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
{id: 2, text: 'item 2', date: '2013-06-23', group: 2},
{id: 3, text: 'item 3', date: '2013-06-25', group: 2},
{id: 4, text: 'item 4'}
]);
// create a DataView
// the view will only contain items having a property group with value 1,
// and will only output fields id, text, and date.
var view = new vis.DataView(data, {
filter: function (item) {
return (item.group == 1);
},
fields: ['id', 'text', 'date']
});
// subscribe to any change in the DataView
view.on('*', function (event, properties, senderId) {
console.log('event', event, properties);
});
// update an item in the data set
data.update({id: 2, group: 1});
// get all ids in the view
var ids = view.getIds();
console.log('ids', ids); // will output [1, 2]
// get all items in the view
var items = view.get();
```
--------------------------------
### Integrate Google Visualization DataTable with vis.DataSet
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This example shows how to load the Google Visualization library, create a Google DataTable, populate it with rows, and then add the entire DataTable directly into a vis.DataSet. This allows for seamless data transfer between the two libraries.
```JavaScript
google.load("visualization", "1");
google.setOnLoadCallback(function () {
var table = new google.visualization.DataTable();
table.addColumn("datetime", "start");
table.addColumn("datetime", "end");
table.addColumn("string", "content");
table.addRows([
[
new Date(2010, 7, 23),
,
"Conversation
" +
'
'
],
[
new Date(2010, 7, 23, 23, 0, 0),
,
"Mail from boss
" +
'
'
],
[new Date(2010, 7, 24, 16, 0, 0), , "Report"],
[new Date(2010, 7, 26), new Date(2010, 8, 2), "Traject A"],
[
new Date(2010, 7, 28),
,
"Memo
" +
'
'
],
[
new Date(2010, 7, 29),
,
"Phone call
" +
'
'
],
[new Date(2010, 7, 31), new Date(2010, 8, 3), "Traject B"],
[
new Date(2010, 8, 4, 12, 0, 0),
,
"Report
" +
'
'
]
]);
dataset.add(table);
});
```
--------------------------------
### Subscribe to All vis.DataSet Events with Named Listener
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This example shows how to subscribe to all events ('*') on a vis.DataSet with a named listener. The listener is associated with a specific 'entityId' and logs events only if the item ID does not match the entityId.
```JavaScript
var entityId = "123";
dataset.subscribe(
"*",
function (event, params, id) {
if (id != entityId) {
console.log("named listener ", event, params, id);
}
},
entityId
);
```
--------------------------------
### JavaScript Example: Subscribing to DataSet Events
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Demonstrates how to subscribe to and unsubscribe from DataSet events using `on` and `off` methods. Shows how different data manipulation operations trigger specific events like 'add', 'update', and 'remove'.
```JavaScript
// create a DataSet
var data = new vis.DataSet();
// subscribe to any change in the DataSet
data.on('*', function (event, properties, senderId) {
console.log('event:', event, 'properties:', properties, 'senderId:', senderId);
});
// triggers an 'add' event
data.add({ id: 1, text: "item 1 (new)" });
// triggers an 'update' event
data.updateOnly({ id: 1, text: "item 1 (updated)" });
// triggers an 'update' event
data.update({ id: 1, text: "item 1 (updated again)" });
// triggers an 'add' event
data.update({ id: 2, text: "item 2 (new)" });
// triggers 'add' and 'update' events
data.update(
{ id: 1, text: "item 1 (updated once more)" },
{ id: 3, text: "item 3 (new)" }
);
// triggers an 'remove' event
data.remove(1);
```
--------------------------------
### JavaScript Example: Constructing a DataPipe with Chained Methods
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This snippet illustrates the construction of a DataPipe using various chainable methods like `filter`, `map`, and `flatMap`. It shows how to define a pipeline for transforming data from a source DataSet or DataView to a target DataSet, allowing for complex data manipulation.
```javascript
const pipe = createNewDataPipeFrom(sourceDataSet)
.filter(item => item.enabled === true)
.map(item => ({
/* some new item */
}))
.flatMap(item => [
/* zero or more new items */
])
.to(targetDataSet);
```
--------------------------------
### Subscribe to All vis.DataSet Events with Anonymous Listener
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This snippet demonstrates how to subscribe to all events ('*') on a vis.DataSet using an anonymous callback function. The listener logs the event type, parameters, and item ID if available.
```JavaScript
dataset.subscribe("*", function (event, params, id) {
if (id != undefined) {
console.log("anonymous listener ", event, params, id);
}
});
```
--------------------------------
### DataSet Data Selection API: get, getIds, forEach, map
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
This section details the API for retrieving and iterating over data in a DataSet. Methods like `get`, `getIds`, `forEach`, and `map` allow flexible data access, supporting various options for filtering, formatting, ordering, and return types.
```APIDOC
DataSet.get([id] [, options]);
DataSet.getIds([options]);
DataSet.forEach(callback [, options]);
DataSet.map(callback [, options]);
Options Object Properties:
- Name: fields
Type: String[] | Object.
Required: no
Description: An array with field names, or an object with current field name and new field name that the field is returned as. By default, all properties of the items are emitted. When `fields` is defined, only the properties whose name is specified in `fields` will be included in the returned items.
- Name: type
Type: Object.
Required: no
Description: An object containing field names as key, and data types as value. By default, the type of the properties of an item are left unchanged. When a field type is specified, this field in the items will be converted to the specified type. This can be used for example to convert ISO strings containing a date to a JavaScript Date object, or convert strings to numbers or vice versa. The available data types are listed in section [Data Types](#Data_Types).
- Name: filter
Type: Function
Required: no
Description: Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. See section [Data Filtering](#Data_Filtering).
- Name: order
Type: String | Function
Required: no
Description: Order the items by a field name or custom sort function.
- Name: returnType
Type: String
Required: no
Description: Determine the type of output of the get function. Allowed values are 'Array' | 'Object'. The default returnType is an Array. The Object type will return a JSON object with the ID's as keys.
```
--------------------------------
### TypeScript Interfaces for DataPipe Item Structure
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
These TypeScript interfaces illustrate the expected structure of items when using DataPipe, differentiating between application-specific and Vis.js-specific properties to prevent naming conflicts. They serve as a guide for data transformation.
```typescript
// TypeScript interfaces to illustrate the structure of the data:
//
// interface appDSItem {
// id: number | string;
//
// appLabel: string;
// appPosition: number;
//
// visLabel: string;
// visColor: string;
// visX: number;
// visY: number;
// }
//
// interface VisDSItem {
// id: number | string;
// label: string;
// color: string;
// x: number;
// y: number;
// }
```
--------------------------------
### Update Items in vis.DataSet with Named Update
Source: https://github.com/visjs/vis-data/blob/master/test/dataset.html
This snippet illustrates how to update an existing item in a vis.DataSet. The 'update' method is used with an array of items to update and an 'entityId' to associate the update operation.
```JavaScript
dataset.update([{ id: 1, foo: "bar" }], entityId);
```
--------------------------------
### Get Filtered and Formatted Data from DataView
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Retrieves items from the DataView, applying a filter function and selecting specific fields. This allows for dynamic data selection and formatting.
```JavaScript
var items = view.get({
fields: ['id', 'score'],
filter: function (item) {
return (item.score > 50);
}
});
```
--------------------------------
### DataSet Supported Data Types API
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
This section lists the various data types supported by the DataSet for item properties, including JavaScript primitives, Date objects, Moment objects, and specific string formats like ISO and ASP Dates, along with examples.
```APIDOC
Name: Boolean
Description: A JavaScript Boolean
Examples: true, false
Name: Number
Description: A JavaScript Number
Examples: 32, 2.4
Name: String
Description: A JavaScript String
Examples: "hello world", "2013-06-28"
Name: Date
Description: A JavaScript Date object
Examples: new Date(), new Date(2013, 5, 28), new Date(1372370400000)
Name: Moment
Description: A Moment object, created with [moment.js](http://momentjs.com/)
Examples: moment(), moment('2013-06-28')
Name: ISODate
Description: A string containing an ISO Date
Examples: new Date().toISOString(), "2013-06-27T22:00:00.000Z"
Name: ASPDate
Description: A string containing an ASP Date
Examples: "/Date(1372370400000)/", "/Date(1198908717056-0700)/"
Name: Id
Description: Id type of items, JavaScript Number or String
Examples: 7, "7", "I'm an id!"
```
--------------------------------
### Get All Items from DataView
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Retrieves all items currently present in the DataView without any filtering or field selection.
```JavaScript
var items = view.get();
```
--------------------------------
### JavaScript: Filter DataSet Items with Custom Functions
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Items in a DataSet can be filtered using a custom function provided to the `filter` option of the `get` method. The filter function receives an item and must return `true` for items to be included in the result.
```javascript
// retrieve all items having a property group with value 2
var group2 = dataset.get({
filter: function (item) {
return (item.group == 2);
}
});
// retrieve all items having a property balance with a value above zero
var positiveBalance = dataset.get({
filter: function (item) {
return (item.balance > 0);
}
});
```
--------------------------------
### DataPipe Instance Methods Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This section documents the core methods available on a DataPipe instance. These methods control the flow and observation of data through the pipe, allowing for initial data transfer and continuous updates from the source to the target DataSet.
```APIDOC
Method: all()
Return Type: this
Description: Sends all the data from the source DataSet or DataView down the pipe line.
Method: start()
Return Type: this
Description: Starts observing the changes in the source DataSet or DataView and sending them down the pipe line as they happen.
Method: stop()
Return Type: this
Description: Stops observing changes in the source DataSet or DataView.
```
--------------------------------
### vis.js DataSet Constructor API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Detailed API documentation for constructing a `vis.DataSet` instance. It outlines the optional `data` array and `options` object, specifying available configuration properties like `fieldId`, `type` (deprecated), and `queue` with its sub-properties `delay` and `max`.
```APIDOC
Constructor: new vis.DataSet([data] [, options])
Parameters:
data: Array (optional)
Description: An Array with items.
options: Object (optional)
Description: An object which can contain the following properties:
Properties:
fieldId: String
Default: "id"
Description: The name of the field containing the id of the items. When data is fetched from a server which uses some specific field to identify items, this field name can be specified in the DataSet using the option `fieldId`. For example CouchDB uses the field "_id" to identify documents.
type: Object.
Default: none
Description: Deprecated: will be removed in the future. An object containing field names as key, and data types as value. By default, the type of the properties of items are left unchanged. Item properties can be normalized by specifying a field type. This is useful for example to automatically convert stringified dates coming from a server into JavaScript Date objects. The available data types are listed in section Data Types.
queue: Object | boolean
Default: none
Description: Queue data changes ('add', 'update', 'remove') and flush them at once. The queue can be flushed manually by calling `DataSet.flush()`, or can be flushed after a configured delay or maximum number of entries.
Properties (when queue is an object):
delay: number
Description: The queue will be flushed automatically after an inactivity of this delay in milliseconds. Default value is `null`.
max: number
Description: When the queue exceeds the given maximum number of entries, the queue is flushed automatically. Default value is `Infinity`.
```
--------------------------------
### DataView Constructor API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Documents the constructor for `vis.DataView`, detailing its parameters (`dataset`, `options`) and the available properties within the `options` object (`convert`, `fields`, `filter`). These options are used for initial filtering and field selection.
```APIDOC
vis.DataView(dataset, options)
Parameters:
dataset: DataSet | DataView
Description: The DataSet or DataView to connect to.
options: Object
Description: An object containing configuration properties.
Properties:
convert: Object. (Default: none)
Description: An object mapping field names to data types for conversion (e.g., 'date' to JavaScript Date object).
fields: String[] | Object. (Default: none)
Description: An array of field names to include, or an object for field renaming.
filter: function (item): boolean (Default: none)
Description: A function to filter items. Returns true for items to include.
```
--------------------------------
### vis.js DataSet Methods API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Comprehensive API documentation for the methods available on a `vis.DataSet` instance. It covers `add`, `clear`, `distinct`, and `flush`, detailing their parameters, return types, and functionality for data manipulation and querying.
```APIDOC
Method: add(data [, senderId])
Return Type: Id[]
Description: Add one or multiple items to the DataSet. `data` can be a single item or an array with items. Adding an item will fail when there already is an item with the same id. The function returns an array with the ids of the added items. See section Data Manipulation.
Method: clear([senderId])
Return Type: Id[]
Description: Clear all data from the DataSet. The function returns an array with the ids of the removed items.
Method: distinct(field)
Return Type: Array
Description: Find all distinct values of a specified field. Returns an unordered array containing all distinct values. If data items do not contain the specified field are ignored.
Method: flush()
Return Type: none
Description: Flush queued changes. Only available when the DataSet is configured with the option `queue`, see section Construction.
```
--------------------------------
### vis.DataSet Event Subscription and Callback Handling
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Details the events available for subscription in `vis.DataSet` and the structure of the callback function used to handle these events, including the types and descriptions of its parameters.
```APIDOC
Events:
add: Triggered when an item or a set of items is added, or when an item is updated while not yet existing.
update: Triggered when an existing item or a set of existing items is updated.
remove: Triggered when an item or a set of items is removed.
*: Triggered when any of the events add, update, and remove occurs.
```
```javascript
function (event, properties, senderId) {
// handle the event
}
```
```APIDOC
Callback Parameters:
event: String
Description: Any of the available events: `add`, `update`, or `remove`.
properties: Object | null
Description: Optional properties providing more information on the event. In case of `add`, `update`, and `remove`, `properties` is an object containing `items` (array of affected item IDs). `update` and `remove` events have `oldData` (original data). `update` event also contains `data` (changes).
senderId: String | Number
Description: An senderId, optionally provided by the application code which triggered the event. If not provided, the argument will be `null`.
```
--------------------------------
### DataSet.setOptions Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Sets configuration options for the DataSet. Allows configuring a queue for data changes with delay and maximum entry limits. Setting 'queue' to false flushes and removes an existing queue.
```APIDOC
setOptions(options)
Parameters:
options: object - Available options:
queue: boolean | object
delay: number (milliseconds) - The queue will be flushed automatically after an inactivity of this delay. Default: null.
max: number (entries) - When the queue exceeds this number of entries, it is flushed automatically. Default: Infinity.
Returns: none
```
--------------------------------
### Perform Basic Data Manipulation in vis.DataSet
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Demonstrates the fundamental operations of creating a `vis.DataSet` and then adding, updating, and removing items using the `add`, `updateOnly`, and `remove` methods.
```javascript
// create a DataSet
var data = new vis.DataSet();
// add items
data.add([
{id: 1, text: 'item 1'},
{id: 2, text: 'item 2'},
{id: 3, text: 'item 3'}
]);
// update an item
data.updateOnly({id: 2, text: 'item 2 (updated)'});
// remove an item
data.remove(3);
```
--------------------------------
### DataSet.on Event Subscription Details
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Detailed syntax and parameter descriptions for subscribing to DataSet events. The `event` parameter specifies the event type, and `callback` is the function to be executed when the event occurs.
```APIDOC
DataSet.on(event, callback)
Parameters:
event: String - Any of the events listed in section Events.
callback: Function - A callback function which will be called each time the event occurs, described in section Callback.
```
--------------------------------
### DataSet.on Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Subscribes to an event, adding an event listener. See Subscriptions section for details.
```APIDOC
on(event, callback)
Returns: none
```
--------------------------------
### DataSet.forEach Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Executes a callback function for every item in the dataset. Options for data selection can be applied.
```APIDOC
forEach(callback [, options])
Returns: none
```
--------------------------------
### vis.DataSet.add() Method API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Provides detailed API documentation for the `DataSet.add()` method, including its syntax, accepted `data` argument types (single object or array of objects), and the event triggered upon successful addition. It also notes the error thrown for duplicate IDs.
```APIDOC
DataSet.add(data [, senderId])
Parameters:
data: Object | Array
Description: An Object containing a single item to be added, or an Array containing a list with items to be added. Each item must contain an id.
senderId: String | Number (optional)
Description: An optional senderId to be passed with the triggered 'add' event to all subscribers.
Returns: addedIds (Array)
Behavior:
- Triggers an 'add' event after items are added.
- Throws an Error if an item with the same id as any of the added items already exists.
```
--------------------------------
### Subscribe to DataView Changes
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Demonstrates how to subscribe to events on a DataView instance. This allows applications to react to changes (add, update, remove) occurring within the DataView, similar to DataSet subscriptions.
```JavaScript
// create a DataSet and a view on the data set
var data = new vis.DataSet();
var view = new vis.DataView({
filter: function (item) {
return (item.group == 2);
}
});
// subscribe to any change in the DataView
view.on('*', function (event, properties, senderId) {
console.log('event:', event, 'properties:', properties, 'senderId:', senderId);
});
// add, update, and remove data in the DataSet...
```
--------------------------------
### vis.DataSet.update() Method API Reference (Add if not exists)
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Provides detailed API documentation for the `DataSet.update()` method, which updates existing items or creates new ones if they don't exist. It describes the syntax, `data` argument types, shallow merging behavior, and the events triggered (`add` for new items, `update` for existing ones). It also includes a warning for TypeScript users.
```APIDOC
DataSet.update(data [, senderId])
Parameters:
data: Object | Array
Description: An Object containing a single item to be updated, or an Array containing a list with items to be updated. Each item must contain an id.
senderId: String | Number (optional)
Description: An optional senderId to be passed with the triggered 'add' or 'update' event to all subscribers.
Returns: updatedIds (Array)
Behavior:
- Provided properties are shallowly merged into existing items.
- Creates items if they do not exist.
- Not possible to remove properties through this method.
- Triggers an 'add' event for newly created items and an 'update' event for updated items.
Warning: For TypeScript users, this method can add partial items into the DataSet, which is a hole in type checking.
```
--------------------------------
### DataSet.map Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Applies a mapping function to every item in the DataSet. Supports data selection options.
```APIDOC
map(callback [, options])
Returns: Array
```
--------------------------------
### DataSet.off Event Unsubscription Details
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Detailed syntax and parameter descriptions for unsubscribing from DataSet events. The `event` and `callback` parameters must match those used during subscription.
```APIDOC
DataSet.off(event, callback)
Parameters:
event: String - Corresponds with the event used to subscribe.
callback: Function - Corresponds with the callback used to subscribe.
```
--------------------------------
### DataSet.get Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Retrieves a single item, multiple items, or all items from the DataSet. Supports various options for data selection. Returns null for single non-existent IDs, or an array with nulls for multiple non-existent IDs.
```APIDOC
get([options] [, data])
get(id [,options] [, data])
get(ids [, options] [, data])
Returns: Object | Array
```
--------------------------------
### DataView Properties
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Lists the available properties of the DataView class.
```APIDOC
length: Number - The number of items currently in the DataView.
```
--------------------------------
### JavaScript DataPipe for DataSet Type Coercion
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This snippet demonstrates how to use vis-data's DataPipe to transform data types within a DataSet. It initializes a raw DataSet, defines target types, and then pipes the transformed data into a new DataSet using the previously defined 'convert' function. All subsequent changes to the raw DataSet will also be transformed and piped.
```javascript
const rawDS = new DataSet([
/* raw data with arbitrary types */
{ id: 7, label: 4, date: "2017-09-04" },
{ id: false, label: 4, date: "2017-10-04" },
{ id: "test", label: true, date: "2017-11-04" }
]);
const coercedDS = new DataSet(/* the data with coerced types will be piped here */);
const types = {
id: "string",
label: "string",
date: "Date"
};
const pipe = createNewDataPipeFrom(rawDS)
.map(item =>
Object.keys(item).reduce((acc, key) => {
acc[key] = convert(item[key], types[key]);
return acc;
}, {})
)
.to(coercedDS);
pipe.all().start();
// All items were transformed and piped into visDS and all later changes
// will be transformed and piped as well.
```
--------------------------------
### Converting Data Type in JavaScript
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This utility function converts an input object to a specified target type, supporting conversions to Boolean, Number, String, Date, Moment.js objects, ISO 8601 Date strings, and ASP.NET Date strings. It intelligently handles various input formats (e.g., numbers, strings, existing Date objects) and throws an error if a conversion is not possible for the given type.
```javascript
return function convert(object, type) {
let match;
if (object === undefined) {
return undefined;
}
if (object === null) {
return null;
}
if (!type) {
return object;
}
if (!(typeof type === "string") && !(type instanceof String)) {
throw new Error("Type must be a string");
}
//noinspection FallthroughInSwitchStatementJS
switch (type) {
case "boolean":
case "Boolean":
return Boolean(object);
case "number":
case "Number":
if (isString(object) && !isNaN(Date.parse(object))) {
return moment(object).valueOf();
} else {
// @TODO: I don't think that Number and String constructors are a good idea.
// This could also fail if the object doesn't have valueOf method or if it's redefined.
// For example: Object.create(null) or { valueOf: 7 }.
return Number(object.valueOf());
}
case "string":
case "String":
return String(object);
case "Date":
if (isNumber(object)) {
return new Date(object);
}
if (object instanceof Date) {
return new Date(object.valueOf());
} else if (moment.isMoment(object)) {
return new Date(object.valueOf());
}
if (isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])); // parse number
} else {
return moment(new Date(object)).toDate(); // parse string
}
} else {
throw new Error(
"Cannot convert object of type " + getType(object) + " to type Date"
);
}
case "Moment":
if (isNumber(object)) {
return moment(object);
}
if (object instanceof Date) {
return moment(object.valueOf());
}
else if (moment.isMoment(object)) {
return moment(object);
}
if (isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return moment(Number(match[1])); // parse number
} else {
return moment(object); // parse string
}
}
else {
throw new Error(
"Cannot convert object of type " + getType(object) + " to type Date"
);
}
case "ISODate":
if (isNumber(object)) {
return new Date(object);
} else if (object instanceof Date) {
return object.toISOString();
} else if (moment.isMoment(object)) {
return object.toDate().toISOString();
} else if (isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])).toISOString(); // parse number
} else {
return moment(object).format(); // ISO 8601
}
} else {
throw new Error(
"Cannot convert object of type " +
getType(object) +
" to type ISODate"
);
}
case "ASPDate":
if (isNumber(object)) {
return "/Date(" + object + ")/";
} else if (object instanceof Date || moment.isMoment(object)) {
return "/Date(" + object.valueOf() + ")/";
} else if (isString(object)) {
match = ASPDateRegex.exec(object);
let value;
if (match) {
// object is an ASP date
value = new Date(Number(match[1])).valueOf(); // parse number
} else {
value = new Date(object).valueOf(); // parse string
}
return "/Date(" + value + ")/";
} else {
throw new Error(
"Cannot convert object of type " +
getType(object) +
```
--------------------------------
### JavaScript: Retrieve DataSet Items by ID or All
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
The `DataSet.get()` method allows retrieving items. It can fetch a single item by its ID, multiple items by an array of IDs, or all items when called without any arguments.
```javascript
var item1 = dataset.get(1);
var items = dataset.get([1, 3, 4]); // retrieve items 1, 3, and 4
var items = dataset.get(); // retrieve all items
```
--------------------------------
### vis.DataSet.updateOnly() Method API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Provides detailed API documentation for the `DataSet.updateOnly()` method, outlining its syntax, accepted `data` argument types, and how properties are merged. It specifies that an exception is thrown if an item does not exist and mentions the `DELETE` symbol for property removal.
```APIDOC
DataSet.updateOnly(data [, senderId])
Parameters:
data: Object | Array
Description: An Object containing a single item to be updated, or an Array containing a list with items to be updated. Each item must contain an id.
senderId: String | Number (optional)
Description: An optional senderId to be passed with the triggered 'update' event to all subscribers.
Returns: updatedIds (Array)
Behavior:
- Provided properties are deeply merged into existing items.
- Throws an exception if an item does not exist.
- Properties can be deleted by assigning them the `DELETE` symbol.
- Triggers an 'update' event after items are updated.
```
--------------------------------
### JavaScript: Deprecated Type Coercion Implementation Details
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This code block represents the original, now deprecated, implementation for type coercion within DataSets. It includes utility functions for checking data types and parsing ASP.Net Date patterns, demonstrating how data transformations were handled before DataPipe was introduced.
```javascript
// --[BEGIN]-- The original implementation of type coercion.
// !!!! Make sure to import Moment.js as this code depends on it.
const convert = (() => {
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
const ASPDateRegex = /^\\/?Date\\((-?\\d+)/i;
/**
* Test whether given object is a number
*
* @param value - Input value of unknown type.
*
* @returns True if number, false otherwise.
*/
function isNumber(value) {
return value instanceof Number || typeof value === "number";
}
/**
* Test whether given object is a string
*
* @param value - Input value of unknown type.
*
* @returns True if string, false otherwise.
*/
function isString(value) {
return value instanceof String || typeof value === "string";
}
/**
* Get the type of an object, for example exports.getType([]) returns 'Array'
*
* @param object - Input value of unknown type.
*/
```
--------------------------------
### JavaScript Type Coercion Function Fragment
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This code fragment shows the concluding part of a JavaScript utility function responsible for coercing values to specific types like string, number, boolean, Date, and ASPDate. It includes error handling for unknown types or invalid ASPDate conversions, indicating the end of the original implementation.
```javascript
" to type ASPDate"
);
}
default:
throw new Error(`Unknown type ${type}`);
}
};
})();
```
--------------------------------
### DataSet.min Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Finds the item with the minimum numeric value for a specified field. Returns null if no item is found or no numeric value exists.
```APIDOC
min(field)
Returns: Object | null
```
--------------------------------
### DataView setData Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataview.html
Replaces the internal DataSet of the DataView. The `data` parameter can be either a DataSet or another DataView instance.
```APIDOC
setData(data)
data: DataSet | DataView - The new data source to set.
```
--------------------------------
### DataSet.update Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Updates one or multiple existing items. If an item does not exist, it will be created. Returns an array with the IDs of the updated/created items. Refer to Data Manipulation for more information.
```APIDOC
update(data [, senderId])
Returns: Id[]
```
--------------------------------
### DataSet.off Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Unsubscribes from a previously registered event listener. See Subscriptions section for details.
```APIDOC
off(event, callback)
Returns: none
```
--------------------------------
### DataSet.getDataSet Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Returns the DataSet itself. For a DataView, this does not return the connected DataSet.
```APIDOC
getDataSet()
Returns: DataSet
```
--------------------------------
### DataSet.updateOnly Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Updates one or multiple existing items. Throws an exception if an item does not exist. Returns an array with the IDs of the updated items. Refer to Data Manipulation for more information.
```APIDOC
updateOnly(data [, senderId])
Returns: Id[]
```
--------------------------------
### vis.DataSet.remove() Method API Reference
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Provides detailed API documentation for the `DataSet.remove()` method, covering its syntax, accepted `id` argument types (Number, String, Object, or Array of ids/items), and its behavior regarding non-existing items. It specifies the return value and the event triggered.
```APIDOC
DataSet.remove(id [, senderId])
Parameters:
id: Number | String | Object | Array
Description: The id of a single item, an item object (deleted by its id), or an Array containing ids or items to be removed.
senderId: String | Number (optional)
Description: An optional senderId to be passed with the triggered 'remove' event to all subscribers.
Returns: removedIds (Array)
Description: An array containing the ids of the items which were actually removed from the DataSet.
Behavior:
- Ignores removal of non-existing items.
- Triggers a 'remove' event for the removed items.
```
--------------------------------
### Detecting Data Type in JavaScript
Source: https://github.com/visjs/vis-data/blob/master/docs/data/datapipe.html
This function accurately determines the precise type of a given JavaScript object, handling primitives, built-in objects like Date and Array, and special cases such as null. It returns a string representing the detected type, providing more specific results than the standard `typeof` operator for complex types.
```javascript
function getType(object) {
const type = typeof object;
if (type === "object") {
if (object === null) {
return "null";
}
if (object instanceof Boolean) {
return "Boolean";
}
if (object instanceof Number) {
return "Number";
}
if (object instanceof String) {
return "String";
}
if (Array.isArray(object)) {
return "Array";
}
if (object instanceof Date) {
return "Date";
}
return "Object";
}
if (type === "number") {
return "Number";
}
if (type === "boolean") {
return "Boolean";
}
if (type === "string") {
return "String";
}
if (type === undefined) {
return "undefined";
}
return type;
}
```
--------------------------------
### DataSet.getIds Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Retrieves IDs of all items or a filtered set of items. Data selection options apply, except 'fields' and 'type'.
```APIDOC
getIds([options])
Returns: Id[]
```
--------------------------------
### DataSet.max Method
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Finds the item with the maximum numeric value for a specified field. Returns null if no item is found or no numeric value exists.
```APIDOC
max(field)
Returns: Object | null
```
--------------------------------
### DataSet.length Property
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
Represents the total number of items currently stored in the DataSet.
```APIDOC
length
Type: Number
Description: The number of items in the DataSet.
```
--------------------------------
### Clear DataSet: Remove All Items
Source: https://github.com/visjs/vis-data/blob/master/docs/data/dataset.html
The `DataSet.clear()` method removes all items from the DataSet. It can optionally accept a `senderId` which is passed along with the `remove` event triggered for all removed items.
```javascript
var removedIds = DataSet.clear([senderId])
```