Svelte: How to set/get data within custom method? (this.set/get not working)

Created on 11 Dec 2016  Â·  6Comments  Â·  Source: sveltejs/svelte

Not sure if this is a bug or I'm doing it wrong, but this.set and this.get within a custom method do not appear to work. Or am I doing this wrong?

e.g., the following doesn't work in REPL

<h1>Hello {{name1}}!</h1>
<h1>Hello {{name2}}!</h1>
<button on:click='swap()'>Swap!</button>

<script>
    export default {
        data () {
            return {
                name1: 'Joe',
                name2: 'Bob'
            }
        },
        methods: {
            swap: () => {
                let nameA = this.get('name1');
                let nameB = this.get('name2');
                this.set({name1: nameB, name2: nameA});
            }
        }
    }
</script>
enhancement

Most helpful comment

The validator should probably throw an error here.

All 6 comments

The validator should probably throw an error here.

Alternative (ES 5):

methods: {
  foo: function(ab, cd) {

  }
}

The validator should probably throw an error here.

Yes, this is a good idea. I'd say warning rather than error because there are occasions when you don't need this (e.g. log: msg => console.log(msg), but that would be useful information to provide

Actually, we can improve on that – if the arrow function expression doesn't use this or arguments, no problem. If it does, error.

Oh wow, good point. Thanks for the fast turn-around on this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Rich-Harris picture Rich-Harris  Â·  3Comments

clitetailor picture clitetailor  Â·  3Comments

st-schneider picture st-schneider  Â·  3Comments

matt3224 picture matt3224  Â·  3Comments

noypiscripter picture noypiscripter  Â·  3Comments