DoneJS StealJS jQuery++ FuncUnit DocumentJS
6.0.1
5.33.2 4.3.0 3.14.1 2.3.35
  • About
  • Guides
  • API Docs
  • Community
  • Contributing
  • Bitovi
    • Bitovi.com
    • Blog
    • Design
    • Development
    • Training
    • Open Source
    • About
    • Contact Us
  • About
  • Guides
  • API Docs
    • Observables
      • can-bind
      • can-compute
      • can-debug
      • can-deep-observable
      • can-define
      • can-define/list/list
      • can-define/map/map
      • can-define-backup
      • can-define-stream
      • can-define-stream-kefir
      • can-event-queue
      • can-kefir
      • can-list
      • can-map
      • can-map-compat
      • can-map-define
      • can-observable-array
        • static
          • convertsTo
          • propertyDefaults
          • items
        • prototype
          • filter
          • serialize
      • can-observable-object
      • can-observation
      • can-observation-recorder
      • can-observe
      • can-simple-map
      • can-simple-observable
      • can-stream
      • can-stream-kefir
      • can-value
    • Views
      • can-attribute-observable
      • can-component
      • can-observable-bindings
      • can-stache
      • can-stache-bindings
      • can-stache-converters
      • can-stache-element
      • can-stache-route-helpers
      • can-view-autorender
      • can-view-callbacks
      • can-view-import
      • can-view-model
      • can-view-parser
      • can-view-scope
      • can-view-target
      • steal-stache
    • Data Modeling
      • can-connect
      • can-connect-feathers
      • can-connect-ndjson
      • can-connect-tag
      • can-define-realtime-rest-model
      • can-define-rest-model
      • can-fixture
      • can-fixture-socket
      • can-local-store
      • can-memory-store
      • can-ndjson-stream
      • can-query-logic
      • can-realtime-rest-model
      • can-rest-model
      • can-set-legacy
      • can-super-model
    • Routing
      • can-deparam
      • can-param
      • can-route
      • can-route-hash
      • can-route-mock
      • can-route-pushstate
    • JS Utilities
      • can-assign
      • can-define-lazy-value
      • can-diff
      • can-globals
      • can-join-uris
      • can-key
      • can-key-tree
      • can-make-map
      • can-parse-uri
      • can-queues
      • can-string
      • can-string-to-any
      • can-zone-storage
    • DOM Utilities
      • can-ajax
      • can-attribute-encoder
      • can-child-nodes
      • can-control
      • can-dom-data
      • can-dom-events
      • can-dom-mutate
      • can-event-dom-enter
      • can-event-dom-radiochange
      • can-fragment
    • Data Validation
      • can-define-validate-validatejs
      • can-type
      • can-validate
      • can-validate-interface
      • can-validate-legacy
      • can-validate-validatejs
    • Typed Data
      • can-cid
      • can-construct
      • can-construct-super
      • can-data-types
      • can-namespace
      • can-reflect
      • can-reflect-dependencies
      • can-reflect-promise
      • can-types
    • Polyfills
      • can-symbol
      • can-vdom
    • Core
    • Infrastructure
      • can-global
      • can-test-helpers
    • Ecosystem
    • Legacy
  • Community
  • Contributing
  • GitHub
  • Twitter
  • Chat
  • Forum
  • News
Bitovi

can-observable-array

  • npm package badge
  • Star
  • Edit on GitHub

Create observable arrays with defined properties.

class extends ObservableArray

Creates a derived class extending from ObservableArray. Useful for creating typed lists to use with associated typed objects.

import { ObservableArray, ObservableObject, type } from "can/everything";

class Todo extends ObservableObject {
  static props = {
    label: String
  };
}

class TodoList extends ObservableArray {
  static items = type.convert(Todo);
}

let todos = new TodoList([
  { label: "Walk the dog" },
  { label: "Make dinner" }
]);

console.log(todos[0] instanceof Todo); // -> true

Returns

{Constructor}:

An extended ObservableArray constructor with definitions from props.

new ObservableArray([items])

Creates an instance of a ObservableArray or an extended ObservableArray with enumerated properties from items.

import { ObservableArray } from "can/everything";

const people = new ObservableArray(
  { first: "Justin", last: "Meyer" },
  { first: "Paula", last: "Strozak" }
);

Parameters

  1. items {Array}:

    Array of items to be added to the array. If items is defined, each item will run through the type converter.

Returns

{can-observable-array}:

An instance of ObservableArray with the values from items.

Mixed-in instance methods and properties

Instances of ObservableArray have all methods and properties from can-event-queue/map/map:

  • addEventListener - Register an event handler to be called when an event is dispatched.

  • @can.getWhatIChange - Return observables whose values are affected by attached event handlers

  • @can.isBound - Return if the observable is bound to.

  • @can.offKeyValue - Unregister an event handler to be called when an event is dispatched.

  • @can.onKeyValue - Register an event handler to be called when a key value changes.

  • dispatch - Dispatch event and key binding handlers.

  • listenTo - Listen to an event and register the binding for simplified unbinding.

  • off - A shorthand method for unbinding an event.

  • on - A shorthand method for listening to event.

  • one - Register an event handler that gets called only once.

  • removeEventListener - Unregister an event handler to be called when an event is dispatched.

  • stopListening - Stops listening for registered event handlers.

Example:

class MyArray extends ObservableArray {
  static items = String;
}

const listInstance = new MyArray(["a", "b"]);

listInstance.on( "length", function( event, newLength, oldLength ) { /* ... */ } );

Mixed-in type methods and properties

Extended ObservableArray classes have all methods and properties from can-event-queue/type/type:

  • @can.offInstanceBoundChange - Stop listening to when an instance's bound status changes.

  • @can.offInstancePatches - Stop listening to patch changes on any instance.

  • @can.onInstanceBoundChange - Listen to when any instance is bound for the first time or all handlers are removed.

  • @can.onInstancePatches - Listen to patch changes on any isntance.

Example:

class MyArray extends ObservableArray {
  static items = String;
}

canReflect.onInstancePatches( MyList, ( instance, patches ) => {

} );

Using

The can-observable-array package exports a ObservableArray class. It can be used with new to create observable lists. For example:

import { ObservableArray } from "can/everything";
const list = new ObservableArray([ "a", "b", "c" ]);
console.log(list[ 0 ]); //-> "a";

list.push( "x" );
list.pop(); //-> "x"

It can also be extended to define custom observable list types with extends. For example, the following defines a StringList type where every item is converted to a string by specifying the items definition:

import { ObservableArray, type } from "can/everything";

class StringList extends ObservableArray {
  static items = {
    type: type.convert(String)
  }
}

const strings = new StringList([ 1, new Date( 1475370478173 ), false ]);

console.log(strings[ 0 ]); //-> "1"
console.log(strings[ 1 ]); //-> "Sat Oct 01 2016 20:07:58 GMT-0500 (CDT)"
console.log(strings[ 2 ]); //-> "false"

Non-numeric properties can also be defined on custom ObservableArray type. The following defines a completed property that returns the completed todos:

import { ObservableArray, ObservableObject, type } from "can/everything";

class Todo extends ObservableObject {
  static props = {
    complete: false
  };
}

class TodoList extends ObservableArray {
  static items = type.convert(Todo);
  get completed() {
    return this.filter( { complete: true } );
  }
}

const todos = new TodoList([ { complete: true }, { complete: false } ]);
console.log(todos.completed.length); //-> 1

Finally, ObservableArray instances are observable, so you can use the can-event-queue/map/map methods to listen to its [can-observable-array/AddEvent], [can-observable-array/LengthEvent], [can-observable-array/RemoveEvent], and [can-observable-array/PropertyNameEvent] events:

import { ObservableArray } from "can/everything";
const people = new ObservableArray([ "alice", "bob", "eve" ]);

people.on( "add", ( ev, items, index ) => {
    console.log( "add", items, index );
} ).on( "remove", ( ev, items, index ) => {
    console.log( "remove", items, index );
} ).on( "length", ( ev, newVal, oldVal ) => {
    console.log( "length", newVal, oldVal );
} );

people.pop(); // remove ["eve"] 2
// length 2 3

people.unshift( "Xerxes" ); // add ["Xerxes"] 1
// length 3 2

CanJS is part of DoneJS. Created and maintained by the core DoneJS team and Bitovi. Currently 6.0.1.

On this page

Get help

  • Chat with us
  • File an issue
  • Ask questions
  • Read latest news