DoneJS StealJS jQuery++ FuncUnit DocumentJS
4.3.0
5.0.0 3.13.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-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-define
      • can-observation
      • can-observation-recorder
      • can-observe
        • Properties
          • defineProperty
          • Array
          • Object
        • Decorators
          • async
          • resolver
        • Object Behaviors
          • @can.isBound
          • @can.offKeyValue
          • @can.offPatches
          • @can.onKeyValue
          • @can.onPatches
        • Array Behaviors
          • pop
          • push
          • reverse
          • shift
          • sort
          • splice
          • unshift
        • Function Behaviors
          • @can.computedPropertyDefinitions
          • @can.defineInstanceKey
          • @can.offInstanceBoundChange
          • @can.offInstancePatches
          • @can.onInstanceBoundChange
          • @can.onInstancePatches
      • can-simple-map
      • can-simple-observable
      • can-stream
      • can-stream-kefir
      • can-value
    • Data Modeling
      • can-connect
      • can-connect-feathers
      • can-fixture
      • can-fixture-socket
      • can-ndjson-stream
      • can-set
    • Views
      • can-component
      • can-stache
      • can-stache-bindings
      • can-stache-converters
      • can-stache-route-helpers
      • can-view-autorender
      • can-view-callbacks
      • can-view-import
      • can-view-live
      • can-view-model
      • can-view-nodelist
      • can-view-parser
      • can-view-scope
      • can-view-target
      • react-view-model
      • react-view-model/component
      • steal-stache
    • 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-util
      • can-zone
      • 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-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

defineProperty

  • Edit on GitHub

Define a rich property behavior on a proxy-wrapped object.

observe.defineProperty( target, property, fn )

Defining your own behaviors should be as easy as possible: There is an defineProperty helper which accepts the target object, the property name, and a function that returns a single-value observable (ie: it implements can.getValue, can.setValue, can.onValue, and can.offValue). For more specifics on how one might create single-value observables, see can-simple-observable.

Parameters

  1. target {Object}:

    A proxy-wrapped object or the prototype of a class which extends Object or Array.

  2. property {String}:

    The name of the property where this behavior should apply.

  3. fn {function}:

    A function which returns a single-value observable.

    Note: target can be an instance (such as the output of observe({})) or a class (such as class extends ObserveObject). If target is a class, it will put this method on the prototype, so all instances get this new behavior.

    import Observation from "can-observation";
    
    observe.defineProperty( target, "name", function( instance, property ) {
        return canReflect.assignSymbols( {}, {
            "can.getValue": function() { /* ... */ },
            "can.setValue": function( value ) { /* ... */ },
            "can.onValue": function( handler ) { /* ... */ },
            "can.offValue": function( handler ) { /* ... */ }
        } );
    } );
    

Using decorators with defineProperty

One of the features provided by the latest-and-greatest (and bleeding edge) ECMA is decorators; in this case, they allow for a very concise way to insert computed properties into a class definition. In addition to being able to create your own, we have also provided a few built-in decorators ([can-observe/decorators/async] and [can-observe/decorators/resolver]).

import Observation from "can-observation";

// generally, this function would come from a different file
function decorate( target, key, descriptor ) {
    const method = descriptor.value;
    observe.defineProperty( target, key, function( instance, property ) {
        return new Observation( method, instance );
    } );
}

class Person extends ObserveObject {
    @decorate
    fullName() {
        return this.first + " " + this.last;
    }
}

Note: the specific example above is equivalent to our built-in automatic observability of getters on classes: simply defining fullName as a getter would give the functionality that the example decorator is providing.

Example: type checking

import { ObserveObject, defineProperty } from "can-observe";
import SimpleObservable from "can-simple-observable";

function type(type) {
    return function checkType( target, key, descriptor ) {
        const method = descriptor.value;
        defineProperty( target, key, function( instance, property ) {
            var value = new SimpleObservable();

            return canReflect.assignSymbols( {}, {
                "can.setValue": function( newValue ) {
                    if( typeof newValue !== type ) {
                        throw new Error( `Value set at ${key} on ${canReflect.getName(this)} must be of type ${type}.` );
                    }

                    return value.set( newValue );
                },
                "can.getValue": value.get.bind( value ),
                "can.onValue": value.on.bind( value ),
                "can.offValue": value.off.bind( value )
            } );
        } );
    }
}

class Person extends ObserveObject {
    @type("string")
    name = "Christopher"
}

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

On this page

Get help

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