4

What is required to define a custom event for a UI plugin in NativeScript?

What I'm trying to achieve is to trigger a foo event that works similar to the tap event on a Button and can be hooked into as follows:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"
      xmlns:fooplugin="nativescript-foo-plugin">
  <StackLayout>
    <Button text="Tap Me!" tap="{{ onTap }}" />
    <fooplugin:FooPlugin foo="{{ onFoo }}" />
  </StackLayout>
</Page>

What I've done essentially boils down to calling the notify function with the eventName value of foo from within the plugin code (ignoring memory leak considerations):

import * as view from 'ui/core/view';

export class FooPlugin extends view.View {
  constructor() {
    super();

    setTimeout(() => {
      this.notify({
        eventName: 'foo',
        object: this,
      });

      // also tried this._emit('foo');
    }, 1000);
  }
}

Is there something else that I'm missing and that I need to do to make this work?

Merott
  • 7,189
  • 6
  • 40
  • 52
  • you could make new variable as a reference refer to `this` outside the setTimeout method. For example: ``` var that = this; setTimeout(() => { that.notify({ eventName: 'foo', object: that, });```. http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Nikolay Tsonev Sep 01 '16 at 05:54
  • I could do that, but since I'm using the ES6 arrow syntax, there is no need for that as the context is taken care of automatically. – Merott Sep 01 '16 at 07:06

2 Answers2

8

create a property public static fooEvent="foo" the name of the property is important it should be eventname+ Event now it should work.

Habib Kazemi
  • 2,172
  • 1
  • 24
  • 30
0
  1. create a property of your Event public static fooEvent="foo". The name is important! It has to be eventname + "Event"

  2. overload the on-function in your declaration file index.d.ts or FooPlugin.d.ts

    // Needed when on method is overriden. on(eventNames: string, callback: (data: EventData) => void, thisArg?: any);