ASP.NET MVC Controls
CollectionView Class
File
wijmo.js
Module
wijmo.collections
Derived Classes
PivotCollectionView
Implements
IEditableCollectionView, IPagedCollectionView

Class that implements the ICollectionView interface to expose data in regular JavaScript arrays.

The CollectionView class implements the following interfaces:

To use the CollectionView class, start by declaring it and passing a regular array as a data source. Then configure the view using the filter, sortDescriptions, groupDescriptions, and pageSize properties. Finally, access the view using the items property. For example:

// create a new CollectionView 
var cv = new wijmo.collections.CollectionView(myArray);

// sort items by amount in descending order
var sd = new wijmo.collections.SortDescription('amount', false);
cv.sortDescriptions.push(sd);

// show only items with amounts greater than 100
cv.filter = function(item) { return item.amount > 100 };

// show the sorted, filtered result on the console
for (var i = 0; i < cv.items.length; i++) {
  var item = cv.items[i]; 
  console.log(i + ': ' + item.name + ' ' + item.amount);
}

Constructor

Properties

Methods

Events

Constructor

constructor

constructor(sourceCollection?: any, options?: any): CollectionView

Initializes a new instance of the CollectionView class.

Parameters
Returns
CollectionView

Properties

canAddNew

Gets a value that indicates whether a new item can be added to the collection.

Type
boolean

canCancelEdit

Gets a value that indicates whether the collection view can discard pending changes and restore the original values of an edited object.

Type
boolean

canChangePage

Gets a value that indicates whether the pageIndex value can change.

Type
boolean

canFilter

Gets a value that indicates whether this view supports filtering via the filter property.

Type
boolean

canGroup

Gets a value that indicates whether this view supports grouping via the groupDescriptions property.

Type
boolean

canRemove

Gets a value that indicates whether items can be removed from the collection.

Type
boolean

canSort

Gets a value that indicates whether this view supports sorting via the sortDescriptions property.

Type
boolean

currentAddItem

Gets the item that is being added during the current add transaction.

Type
any

currentEditItem

Gets the item that is being edited during the current edit transaction.

Type
any

currentItem

Gets or sets the current item in the view.

Type
any

currentPosition

Gets the ordinal position of the current item in the view.

Type
number

filter

Gets or sets a callback used to determine if an item is suitable for inclusion in the view.

The callback function should return true if the item passed in as a parameter should be included in the view.

NOTE: If the filter function needs a scope (i.e. a meaningful 'this' value) remember to set the filter using the 'bind' function to specify the 'this' object. For example:

collectionView.filter = this._filter.bind(this);
Type
IPredicate

getError

Gets or sets a callback that determines whether a specific property of an item contains validation errors.

If provided, the callback should take two parameters containing the item and the property to validate, and should return a string describing the error (or null if there are no errors).

For example:

var view = new wijmo.collections.CollectionView(data, {
    getError: function (item, property) {
        switch (property) {
            case 'country':
                return countries.indexOf(item.country) < 0
                    ? 'Invalid Country'
                    : null;
            case 'downloads':
            case 'sales':
            case 'expenses':
                return item[property] < 0
                    ? 'Cannot be negative!'
                    : null;
            case 'active':
                return item.active && item.country.match(/US|UK/)
                    ? 'No active items allowed in the US or UK!'
                    : null;
        }
        return null;
    }
});
Type
Function

groupDescriptions

Gets a collection of GroupDescription objects that describe how the items in the collection are grouped in the view.

Type
ObservableArray

groups

Gets an array of CollectionViewGroup objects that represents the top-level groups.

Type
CollectionViewGroup[]

isAddingNew

Gets a value that indicates whether an add transaction is in progress.

Type
boolean

isEditingItem

Gets a value that indicates whether an edit transaction is in progress.

Type
boolean

isEmpty

Gets a value that indicates whether this view contains no items.

Type
boolean

isPageChanging

Gets a value that indicates whether the page index is changing.

Type
boolean

isUpdating

Gets a value that indicates whether notifications are currently suspended (see beginUpdate and endUpdate).

Type

itemCount

Gets the total number of items in the view taking paging into account.

Type
number

items

Gets items in the view.

Type
any[]

itemsAdded

Gets an ObservableArray containing the records that were added to the collection since trackChanges was enabled.

Type
ObservableArray

itemsEdited

Gets an ObservableArray containing the records that were edited in the collection since trackChanges was enabled.

Type
ObservableArray

itemsRemoved

Gets an ObservableArray containing the records that were removed from the collection since trackChanges was enabled.

Type
ObservableArray

newItemCreator

Gets or sets a function that creates new items for the collection.

If the creator function is not supplied, the CollectionView will try to create an uninitialized item of the appropriate type.

If the creator function is supplied, it should be a function that takes no parameters and returns an initialized object of the proper type for the collection.

Type
Function

pageCount

Gets the total number of pages.

Type
number

pageIndex

Gets the zero-based index of the current page.

Type
number

pageSize

Gets or sets the number of items to display on a page.

Type
number

sortComparer

Gets or sets a function used to compare values when sorting.

If provided, the sort comparer function should take as parameters two values of any type, and should return -1, 0, or +1 to indicate whether the first value is smaller than, equal to, or greater than the second. If the sort comparer returns null, the standard built-in comparer is used.

This sortComparer property allows you to use custom comparison algorithms that in some cases result in sorting sequences that are more consistent with user's expectations than plain string comparisons.

For example, see Dave Koele's Alphanum algorithm. It breaks up strings into chunks composed of strings or numbers, then sorts number chunks in value order and string chunks in ASCII order. Dave calls the result a "natural sorting order".

The example below shows a typical use for the sortComparer property:

// create a CollectionView with a custom sort comparer
var dataCustomSort = new wijmo.collections.CollectionView(data, {
  sortComparer: function (a, b) {
    return wijmo.isString(a) && wijmo.isString(b)
      ? alphanum(a, b) // custom comparer used for strings
      : null; // use default comparer used for everything else
  }
});
Type
Function

sortConverter

Gets or sets a function used to convert values when sorting.

If provided, the function should take as parameters a SortDescription, a data item, and a value to convert, and should return the converted value.

This property provides a way to customize sorting. For example, the FlexGrid control uses it to sort mapped columns by display value instead of by raw value.

For example, the code below causes a CollectionView to sort the 'country' property, which contains country code integers, using the corresponding country names:

var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(',');
collectionView.sortConverter = function (sd, item, value) {
  if (sd.property == 'countryMapped') {
    value = countries[value]; // convert country id into name
  }
  return value;
}
Type
Function

sortDescriptions

Gets a collection of SortDescription objects that describe how the items in the collection are sorted in the view.

Type
ObservableArray

sourceCollection

Gets or sets the underlying (unfiltered and unsorted) collection.

Type
any

totalItemCount

Gets the total number of items in the view before paging is applied.

Type
number

trackChanges

Gets or sets a value that determines whether the control should track changes to the data.

If trackChanges is set to true, the CollectionView keeps track of changes to the data and exposes them through the itemsAdded, itemsRemoved, and itemsEdited collections.

Tracking changes is useful in situations where you need to update the server after the user has confirmed that the modifications are valid.

After committing or cancelling changes, use the clearChanges method to clear the itemsAdded, itemsRemoved, and itemsEdited collections.

The CollectionView only tracks changes made when the proper editItem/commitEdit, addNew/commitNew, and remove). Changes made directly to the data are not tracked.

Type
boolean

useStableSort

Gets or sets whether to use a stable sort algorithm.

Stable sorting algorithms maintain the relative order of records with equal keys. For example, consider a collection of objects with an "Amount" field. If you sort the collection by "Amount", a stable sort will keep the original order of records with the same Amount value.

This property is false by default, which causes the CollectionView to use JavaScript's built-in sort method, which is very fast but not stable. Setting the useStableSort property to true increases sort times by 30% to 50%, which can be significant for large collections.

Type
boolean

Methods

addNew

addNew(): any

Creates a new item and adds it to the collection.

This method takes no parameters. It creates a new item, adds it to the collection, and defers refresh operations until the new item is committed using the commitNew method or canceled using the cancelNew method.

The code below shows how the addNew method is typically used:

// create the new item, add it to the collection
var newItem = view.addNew();

// initialize the new item
newItem.id = getFreshId();
newItem.name = 'New Customer';

// commit the new item so the view can be refreshed
view.commitNew();

You can also add new items by pushing them into the sourceCollection and then calling the refresh method. The main advantage of addNew is in user-interactive scenarios (like adding new items in a data grid), because it gives users the ability to cancel the add operation. It also prevents the new item from being sorted or filtered out of view until the add operation is committed.

Returns
any

beginUpdate

beginUpdate(): void

Suspend refreshes until the next call to endUpdate.

Returns
void

cancelEdit

cancelEdit(): void

Ends the current edit transaction and, if possible, restores the original value to the item.

Returns
void

cancelNew

cancelNew(): void

Ends the current add transaction and discards the pending new item.

Returns
void

clearChanges

clearChanges(): void

Clears all changes by removing all items in the itemsAdded, itemsRemoved, and itemsEdited collections.

Call this method after committing changes to the server or after refreshing the data from the server.

Returns
void

commitEdit

commitEdit(): void

Ends the current edit transaction and saves the pending changes.

Returns
void

commitNew

commitNew(): void

Ends the current add transaction and saves the pending new item.

Returns
void

contains

contains(item: any): boolean

Returns a value indicating whether a given item belongs to this view.

Parameters
  • item: any

    Item to seek.

Returns
boolean

deferUpdate

deferUpdate(fn: Function): void

Executes a function within a beginUpdate/endUpdate block.

The collection will not be refreshed until the function finishes. This method ensures endUpdate is called even if the function throws an exception.

Parameters
  • fn: Function

    Function to be executed without updates.

Returns
void

editItem

editItem(item: any): void

Begins an edit transaction of the specified item.

Parameters
  • item: any

    Item to be edited.

Returns
void

endUpdate

endUpdate(): void

Resume refreshes suspended by a call to beginUpdate.

Returns
void

getAggregate

getAggregate(aggType: Aggregate, binding: string, currentPage?: boolean): void

Calculates an aggregate value for the items in this collection.

Parameters
  • aggType: Aggregate

    Type of aggregate to calculate.

  • binding: string

    Property to aggregate on.

  • currentPage: boolean Optional

    Whether to include only items on the current page.

Returns
void

implementsInterface

implementsInterface(interfaceName: string): boolean

Returns true if the caller queries for a supported interface.

Parameters
  • interfaceName: string

    Name of the interface to look for.

Returns
boolean

moveCurrentTo

moveCurrentTo(item: any): boolean

Sets the specified item to be the current item in the view.

Parameters
  • item: any

    Item that will become current.

Returns
boolean

moveCurrentToFirst

moveCurrentToFirst(): boolean

Sets the first item in the view as the current item.

Returns
boolean

moveCurrentToLast

moveCurrentToLast(): boolean

Sets the last item in the view as the current item.

Returns
boolean

moveCurrentToNext

moveCurrentToNext(): boolean

Sets the item after the current item in the view as the current item.

Returns
boolean

moveCurrentToPosition

moveCurrentToPosition(index: number): boolean

Sets the item at the specified index in the view as the current item.

Parameters
  • index: number

    Index of the item that will become current.

Returns
boolean

moveCurrentToPrevious

moveCurrentToPrevious(): boolean

Sets the item before the current item in the view as the current item.

Returns
boolean

moveToFirstPage

moveToFirstPage(): boolean

Sets the first page as the current page.

Returns
boolean

moveToLastPage

moveToLastPage(): boolean

Sets the last page as the current page.

Returns
boolean

moveToNextPage

moveToNextPage(): boolean

Moves to the page after the current page.

Returns
boolean

moveToPage

moveToPage(index: number): boolean

Moves to the page at the specified index.

Parameters
  • index: number

    Index of the page to move to.

Returns
boolean

moveToPreviousPage

moveToPreviousPage(): boolean

Moves to the page before the current page.

Returns
boolean

onCollectionChanged

onCollectionChanged(e?: NotifyCollectionChangedEventArgs): void

Raises the collectionChanged event.

Parameters
Returns
void

onCurrentChanged

onCurrentChanged(e?: EventArgs): void

Raises the currentChanged event.

Parameters
Returns
void

onCurrentChanging

onCurrentChanging(e: CancelEventArgs): boolean

Raises the currentChanging event.

Parameters
Returns
boolean

onPageChanged

onPageChanged(e?: EventArgs): void

Raises the pageChanged event.

Parameters
Returns
void

onPageChanging

onPageChanging(e: PageChangingEventArgs): boolean

Raises the pageChanging event.

Parameters
Returns
boolean

onSourceCollectionChanged

onSourceCollectionChanged(e?: EventArgs): void

Raises the sourceCollectionChanged event.

Parameters
Returns
void

onSourceCollectionChanging

onSourceCollectionChanging(e: CancelEventArgs): boolean

Raises the sourceCollectionChanging event.

Parameters
Returns
boolean

refresh

refresh(): void

Re-creates the view using the current sort, filter, and group parameters.

Returns
void

remove

remove(item: any): void

Removes the specified item from the collection.

Parameters
  • item: any

    Item to be removed from the collection.

Returns
void

removeAt

removeAt(index: number): void

Removes the item at the specified index from the collection.

Parameters
  • index: number

    Index of the item to be removed from the collection. The index is relative to the view, not to the source collection.

Returns
void

Events

collectionChanged

Occurs when the collection changes.

Arguments
NotifyCollectionChangedEventArgs

currentChanged

Occurs after the current item changes.

Arguments
EventArgs

currentChanging

Occurs before the current item changes.

Arguments
CancelEventArgs

pageChanged

Occurs after the page index changes.

Arguments
EventArgs

pageChanging

Occurs before the page index changes.

Arguments
PageChangingEventArgs

sourceCollectionChanged

Occurs after the value of the sourceCollection property changes.

Arguments
EventArgs

sourceCollectionChanging

Occurs before the value of the sourceCollection property changes.

Arguments
CancelEventArgs

 

 


Copyright © GrapeCity, inc. All rights reserved.

Product Support Forum |  Documentation Feedback