ractivejs / ractive

Next-generation DOM manipulation
http://ractive.js.org
MIT License
5.94k stars 396 forks source link

Ractive.extendWith and "this" #3315

Closed kryptus36 closed 5 years ago

kryptus36 commented 5 years ago

Description:

When creating a widget, I seem unable to call methods using this.

Versions affected:

1.2.4

Platforms affected:

All

Reproduction:

// widget.ts

import {Ractive} from 'ractive';

class Widget extends Ractive {
    method (value: number): void {
        // Do stuff
    }

    anotherMethod(): void {
        this.method(5);  //this.method is undefined???
    }
}

const myWidget = Ractive.extendWith(Widget, {
    template: '<button on-click="@this.anotherMethod()">Click</button>'
});

export default myWidget;
evs-chris commented 5 years ago

In this case, you'll want:

// widget.ts

import { Ractive, InitOpts } from 'ractive';

export default class Widget extends Ractive {
    constructor(opts?: InitOpts) { super(opts); }

    method (value: number): void {
        // Do stuff
    }

    anotherMethod(): void {
        this.method(5);  //this.method is undefined???
    }
}

Ractive.extendWith(Widget, {
    template: '<button on-click="@this.anotherMethod()">Click</button>'
});
kryptus36 commented 5 years ago

Thanks for the reply. I realized in trying to simplify my example I figured out the problem is actually stemming from something a bit deeper in my code.

I'm actually trying to handle a drop event.

Since ractive lacks on-drag* and on-drop events as far as I can tell I had attached the event listener manually, which obviously changes the context of this.

There are some drag and drop plugins but they seem outdated. Are there plans to add events for html 5's drag and drop events?

evs-chris commented 5 years ago

Any html event should already be supported e.g. <div on-drop="@.dropped(@event)">Drop here</div> would call the dropped method on your instance with the drop event. Here's an example.

kryptus36 commented 5 years ago

Thanks for the example. It showed me I'm over complicating it - the drop event does indeed work.