Events

Contents of this article:

Overview

An event is a message sent from an event emitter to signify the occurrence of a specific action. This action can be generated by a user action (such as a tap) or by program logic (for instance, to indicate that downloading an image from a server has completed). The object that raises the event is called an event sender (simply sender) or event raiser. The object that consumes the event is called an event listener (simply listener) or event handler.

The NativeScript framework provides a class Observable that powers the process of working with events. Find more information about it in the API Reference. Because it is one of the base classes within the NativeScript framework, almost every NativeScript object (component) has an option for dealing with events.

Adding an Event Handler

To add an event handler means setting a function (method) that executes when the event is raised.

Example 1 shows how to set a function that prints a "Hello World!" message in the console when a button is tapped. You can choose between the shorthand syntax and the full syntax or you can declare the event handler in XML.

The example below shows how to add an event listener by using the short and full syntax. There is a third optional parameter that represents the this argument.

Example 1 (JavaScript): Adding an event handler or an event listener using the short and full syntax.

//Adding a listener with the short syntax
var buttonModule = require("ui/button");
var testButton = new buttonModule.Button();
testButton.text = "Test";

testButton.on(buttonModule.Button.tapEvent, function (eventData) {
  console.log("Hello World!");
},this);

//Adding a lister with the full syntax
var testButton2 = new buttonModule.Button();
testButton2.text = "Test";

var onTap = function (eventData) {
  console.log("Hello World!");
};

testButton2.addEventListener(buttonModule.Button.tapEvent, onTap, this);

Example 1 (TypeScript): Adding an event handler or an event listener using the short and full syntax.

//Adding a listener with the short syntax
import buttonModule = require("ui/button");
var testButton = new buttonModule.Button();
testButton.text = "Test";

testButton.on(buttonModule.Button.tapEvent, function (eventData) {
  console.log("Hello World!");
  },this);

//Adding a lister with the full syntax
var testButton2 = new buttonModule.Button();
testButton2.text = "Test";

var onTap = function (eventData) {
  console.log("Hello World!");
};

testButton2.addEventListener(buttonModule.Button.tapEvent, onTap, this);

Another option to set an event handler is to use an XML declaration.

Example 1 (XML): Adding an event handler or an event listener using an XML declaration.

<Page>
  <StackLayout>
    <Button tap="onTap" />
  </StackLayout>
</Page>

You need a code-behind file (see Example 2) to write the function body (the code-behind file has the same file name, but a different extension: .js or .ts depending on the language you are using).

Example 2: Hooking to a button tap event

function onTap(eventData) {
  console.log("Hello World!");
}
exports.onTap = onTap;
export function onTap(eventData) {
  console.log("Hello World!");
}

Removing an Event Listener

Usually you don't need to remove the event listener. You might need to do it when you want to receive the event just once or to free up resources. In such cases, you can apply the methods in Example 3.

There is no syntax to remove an event listener through an XML declaration.

Removing an Event Listener Using the Shorthand or Full Syntax

Example 3 uses the shorthand and full syntax to remove all listeners for the tap event of the testButton instance. If more than one object are listening for events, you can set a second parameter with the name of the callback function. This way only the referenced event listener is removed. When multiple event listeners with different this arguments are available, a third optional parameter is used.

Example 3: Removing a button tap event listener

//Removing a listener with short syntax
testButton.off(buttonModule.Button.tapEvent);

//Removing a listener with short syntax
testButton2.removeEventListener(buttonModule.Button.tapEvent);
//Removing a listener with short syntax
testButton.off(buttonModule.Button.tapEvent);

//Removing a listener with short syntax
testButton2.removeEventListener(buttonModule.Button.tapEvent);

PropertyChange Event

The Observable class provides a built-in event called propertyChange that is called when a property is changed. Example 4 shows how to subscribe to this event.

Example 4: Handle the propertyChange event

var observableModule = require("data/observable");
var observableObject = new observableModule.Observable();

observableObject.on(observableModule.Observable.propertyChangeEvent, function(propertyChangeData){
  console.log(propertyChangeData.propertyName + " has been changed and the new value is: " + propertyChangeData.value);
});
import observableModule = require("data/observable");
var observableObject = new observableModule.Observable();

observableObject.on(observableModule.Observable.propertyChangeEvent, function(propertyChangeData){
  console.log(propertyChangeData.propertyName + " has been changed and the new value is: " + propertyChangeData.value);
});

It is important to note that the propertyChange event is critical for the entire data binding system. To take advantage of the data binding mechanism, all you have to do is make your business object inherit the Observable class. Example 5 demonstrates how to do that.

Example 5: Handle the propertyChange event via XML

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
  <StackLayout>
    <Switch checked="" propertyChange="onCheckChange"/>
  </StackLayout>
</Page>
function onCheckChange(args) {
    console.log("Property Changed!");
    console.log("Event name:" + args.eventName);
    console.log("Object:" + args.object);
    console.log("propertyname:" + args.propertyName);
    console.log("value:" + args.value);
}
exports.onCheckChange = onCheckChange;
import { PropertyChangeData } from "data/observable";

export function onCheckChange(args: PropertyChangeData) {
    console.log("Property Changed!");
    console.log("Event name:" + args.eventName);
    console.log("Object:" + args.object);
    console.log("propertyname:" + args.propertyName);
    console.log("value:" + args.value);
}

The code snippet in Example 5 fires the propertyChange event when the switch checked value is changed.

Example 6: Creating a custom class and inheriting Observable class

var observableModule = require("data/observable");
var MyClass = (function (_super) {
  __extends(MyClass, _super);
  function MyClass() {
    _super.apply(this, arguments);
  }
  Object.defineProperty(MyClass.prototype, "myProperty", {
    get: function () {
      return this._myProperty;
      },
      set: function (value) {
        this._myProperty = value;
      },
      enumerable: true,
      configurable: true
    });
    return MyClass;
  })(observableModule.Observable);
exports.MyClass = MyClass;
import observableModule = require("data/observable");

export class MyClass extends observableModule.Observable {
  private _myProperty:number;
  public get myProperty(): number {
    return this._myProperty;
  }

  public set myProperty(value: number) {
    this._myProperty = value;
  }
}

The code snippet in Example 6 fires the propertyChange event when the property value is changed.

Creating a Custom Event

If your business logic demands it, you may want to fire (raise or emit) a custom event on a particular action (see Example 7). To do that, call the Observable.notify() method when the action is completed. This method takes any implementer of the EventData interface as event data. It includes basic information about an event—its name as eventName and an instance of the event sender as object).

Example 7: Creating a custom event.

var eventData = {
  eventName: "myCustomEventName",
  object: this
};
this.notify(eventData);
var eventData: observableModule.EventData = {
  eventName: "myCustomEventName",
  object: this
}
this.notify(eventData);

The minimum information needed to raise an event is the eventName—it will be used to execute all event handlers associated with this event.

The next step is to hook to this event:

var myCustomObject = new MyClass();
myCustomObject.on("myCustomEventName", function(eventData){
  console.log(eventData.eventName + " has been raised! by: " + eventData.object);
})

A similar logic is implemented for the propertyChange event, so if your business logic requires that, propertyChange can be emitted manually through the notify() method (without using the Observable.set() method that also fires the propertyChange event).

Avoiding Memory Leaks

Although the radio station comparison is convenient for understanding the concept, events are a bit more complicated on the inside. To be able to notify the listener, the sender contains a pointer to the listener. Even if you set the listener object to null or undefined, it is not eligible for garbage collection, because the sender is alive and has a live reference to the listener object. This could result in a memory leak when the object lifetimes of the sender and the listener differ significantly.

Consider this scenario: A UI element creates a lot of child controls, each of which hooks to an event of the parent. Then a child control is released (during a list view scrolling for instance), causing a memory leak.

To prevent these memory leaks, it is a good practice to remove your event listener handler before releasing the listener object. Unfortunately, sometimes you cannot determine the exact time to call the off or removeEventListener function. In such cases, use another option of the NativeScript framework: weak events.

Working with Weak Events

A weak event, as its name suggests, creates an weak reference to the listener object, which helps you release the listener object without removing the event listener pointer.

Adding a Weak Event Listener

Using weak event listeners is very similar to normal events. Example 8 shows how to add a weak event listener (code comments are included for clarity):

Example 8: Creating a weak event and handling a property change event

var weakEventListenerModule = require("ui/core/weak-event-listener");
var buttonModule = require("ui/button");
var observableModule = require("data/observable");

var testButton = new buttonModule.Button();
testButton.text = "Test";
testButton.on(buttonModule.Button.tapEvent, function () {
  source.set("testProperty", "change" + counter);
});

var source = new observableModule.Observable();

var counter = 0;
var handlePropertyChange = function () {
  counter++;
  this.text = counter + "";
};

var weakEL = weakEventListenerModule.WeakEventListener;
var weakEventListenerOptions: weakEventListenerModule.WeakEventListenerOptions = {
  // create a weak reference to the event listener object
  targetWeakRef: new WeakRef(this),
  // create a weak reference to the event sender object
  sourceWeakRef: new WeakRef(this.source),
  // set the name of the event
  eventName: observable.Observable.propertyChangeEvent,
  // set the event handler
  handler: handlePropertyChange,
  // (optional) set the context in which to execute the handler 
  handlerContext: testButton,
  // (optional) set a specialized property used for extra event recognition 
  key: this.options.targetProperty
}
weakEL.addWeakEventListener(this.weakEventListenerOptions);
import weakEventListenerModule = require("ui/core/weak-event-listener");
import buttonModule = require("ui/button");
import observableModule = require("data/observable");

var testButton = new buttonModule.Button();
testButton.text = "Test";
testButton.on(buttonModule.Button.tapEvent, function () {
  source.set("testProperty", "change" + counter);
});

var source = new observableModule.Observable();

var counter = 0;
var handlePropertyChange = function () {
  counter++;
  this.text = counter + "";
};

var weakEL = weakEventListenerModule.WeakEventListener;
var weakEventListenerOptions: weakEventListenerModule.WeakEventListenerOptions = {
  // create a weak reference to the event listener object
  targetWeakRef: new WeakRef(this),
  // create a weak reference to the event sender object
  sourceWeakRef: new WeakRef(this.source),
  // set the name of the event
  eventName: observable.Observable.propertyChangeEvent,
  // set the event handler
  handler: handlePropertyChange,
  // specialized property used for extra event recognition
  key: this.options.targetProperty,
  // (optional) set the context in which to execute the handler
  handlerContext: testButton
}
weakEL.addWeakEventListener(this.weakEventListenerOptions);

Example 8 shows how to attach a weak event listener to an observable object instance. A closer look at the handlePropertyChange function shows that text property of the this object is changed when the propertyChange event is raised (via the button tap event). The function demonstrates how to use the handlerContext property—its value is taken as an argument to this inside the event handler function.

Removing a Weak Event Listener

The targetWeakRef and key properties are optional when invoking a function on an event. However, they allow for removing an event listener. The properties are used as keys for a key-value pair that stores weak event listeners.

weakEL.removeWeakEventListener(this.weakEventListenerOptions);
weakEL.removeWeakEventListener(this.weakEventListenerOptions);

Stay connected with NativeScript

(expect a newsletter every 4-8 weeks)

NativeScript
NativeScript is licensed under the Apache 2.0 license .
© Progress Software Corporation. All Rights Reserved.