can-define
Exports the define
method that defines observable properties and their behavior on a prototype object.
define(prototype, propDefinitions)
Define observable properties, type conversion, and getter/setter logic on prototype objects.
import define from "can-define";
const Greeting = function( message ) {
this.message = message;
};
define( Greeting.prototype, {
message: { type: "string" }
} );
Parameters
- prototype
{Object}
:The prototype object of a constructor function or class. The prototype object will have getter/setters defined on it that carry out the defined behavior. The prototype will also contain all of can-event-queue/map/map's methods.
- propDefinitions
{Object<String,PropDefinition>}
:An object of properties and their definitions.
Use
can-define
provides a way to create custom types with observable properties.
Where can-define/map/map and can-define/list/list provide more functionality, they also make
more assumptions on the type constructor. can-define
can be used
to create completely customized types.
The following creates a
Person
constructor function:
import define from "can-define";
const Person = function( first, last ) {
this.first = first;
this.last = last;
};
define( Person.prototype, {
first: { type: "string" },
last: { type: "string" },
fullName: {
get: function() {
return this.first + " " + this.last;
}
}
} );
This can be used to create Person
instances with observable properties:
const person = new Person( "Justin", "Meyer" );
person.first; //-> "Justin"
person.last; //-> "Meyer"
person.fullName; //-> "Justin Meyer"
person.on( "fullName", function( ev, newVal, oldVal ) {
newVal; //-> "Ramiya Meyer"
oldVal; //-> "Justin Meyer"
} );
person.first = "Ramiya";
The observable properties call ObservationRecorder.add so they can be observed by can-compute.