can-symbol
Version:
Well known symbols used to detail how to operate on different objects
42 lines (33 loc) • 1.18 kB
Markdown
*))} can-symbol/symbols/onEmit can.onEmit
can-symbol/symbols/observe
Defines how observables can listen to the object's value whenever it is emitted.
`@ .onEmit( handler(newValue) )`
The `@@@ .onEmit` symbol points to a function that registers
`handler` to be called back with the new value of the object when it
is emitted. `@@@ .onEmit` can be used when you wish to emit a value that isn't changing.
```js
const obj = function(value) {
if(arguments.length >= 1) {
obj.currentValue = value;
obj.handlers.forEach(function(handler){
handler.call(obj, value);
});
} else {
return obj.currentValue;
}
};
obj[canSymbol.for("can.onEmit")] = function(handler){
if(!obj.handlers) {
obj.handlers = [];
}
obj.handlers.push(handler);
}
const listener = function (value) {
console.log('emitted', value);
}
obj[canSymbol.for("can.onEmit")](listener);
obj(5); // -> output: "emitted 5"
obj(5); // -> output: "emitted 5"
```
{*} any object with a mutable value
{function(this:*, *)} handler(newValue) The handler must be called back with `this` as the instance of the observable.
{function(function(