listenTo
Listen to an event and register the binding for simplified unbinding.
obj.listenTo([bindTarget,] event, handler)
.listenTo is useful for creating bindings that can can be torn down with
stopListening. This is useful when creating
rich behaviors that can't be accomplished using computed values, or if you are trying to
avoid streams.
For example, the following creates an observable that counts how many times its
name property has changed:
class Person {
constructor(){
this.nameChanged = 0;
this.listenTo("name", function(){
this.nameChanged++;
})
},
setName(newVal) {
this.name = newVal;
this.dispatch("name",[newVal])
}
}
mixinMapBindings(Person.prototype);
var person = new Person();
person.setName("Justin");
person.setName("Ramiya");
person.nameChanged //-> 2
.listenTo event bindings are stored on an observable and MUST be unbound using
stopListening. .stopListening make it easy to unbind
all of the .listenTo event bindings when the observable is no longer needed:
person.stopListening();
If no bindTarget is passed, .listenTo binds to the current
observable.
can-component's connectedCallback lifecyle hook is often used to call
.listenTo to setup bindings that update viewmodel properties.
Parameters
- bindTarget
{Object}:The object to listen for events on. If
bindTargetis not provided, the observable.listenTowas called on will be thebindTarget. - event
{String}:The name of the event to listen for.
- handler
{function}:The handler that will be executed to handle the event.
Returns
{Object}:
this