kbrsh / moon

🌙 The minimal & fast library for functional user interfaces
https://moonjs.org
MIT License
6k stars 200 forks source link

onCreate() doesn't have access to "this" #248

Closed MelonFunction closed 5 years ago

MelonFunction commented 5 years ago
<h1>{content}</h1>
<button @click={updateContent($event)}>press me</button>

<script>
export default {
    content: "unchanged",

    onCreate(){
                 // Doesn't work
         this.update('content', 'pre button pressed')
    },

    updateContent(){
        axios.get('/api').then(res => {
                        // Works
            this.update('content', res.data.message);
        });
    }
}
</script>

Gives me the error:

TypeError: this is undefined[Learn More] css.967bad95.js line 306 > Function:26:7 

Did I do something wrong?

kbrsh commented 5 years ago

It seems to be working with this reproduction. What version of Moon are you using? Try logging this and verifying if it is undefined.

MelonFunction commented 5 years ago

Moon v1.0.0-beta.2 too. Here it is in component format https://github.com/Lomomn/WebstackTemplate/tree/master/frontend

When I add onCreate like in my example above and console.log(this), this===undefined.

MelonFunction commented 5 years ago

Any ideas?

MelonFunction commented 5 years ago

I also tested this with the moon-cli application and I still get the this===undefined error

kbrsh commented 5 years ago

Looks like a bug. However, I think it has been fixed in 67b32ae39283d7ba6f1b897e8ea9d6c846f52f5f. The way it works using prototypes isn't compatible with the compiler though, but I'm working on it.

I can't think of any workarounds right now, let me know if you find something or have any questions.

kbrsh commented 5 years ago

Using another library would be good for now as Moon becomes a little more stable. Thanks for the bug report :)

kbrsh commented 5 years ago

I don't know of any with a similar API, but check out Preact or Hyperapp. I'd also prefer if you could move this conversation to the Slack and keep GitHub only for discussion on issues :)