1

Problem: I need to set a vue component's event handler equal to the return value of another method.

This JavaScript runs on click.

<!-- pseudo code -->
<input type="button" @click="count + 1">

Method is invoked on click.

<!-- pseudo code -->
<input type="button" @click="addToCount">
...
<script>
function addToCount () {
    count + 1
}
</script>

But this will invoke getAddToCountHandler on click, not addToCount.

<!-- pseudo code -->
<input type="button" @click="getAddToCountHandler()">
...
<script>
function getAddToCountHandler () {
    return function addToCount () {
        count + 1
    }
}
</script>

The following is closer to what I am trying to do, with some variables stored in a closure.

<!-- pseudo code -->
<input type="button" @click="getHandler(0)">
...
<script>
function getHandler (param) {
    let storedParam = param
    return function () {
        storedParam += 1
        console.log(storedParam)
    }
}
</script>

1 Answer 1

1

You should run the return function as follows by adding () like :

<input type="button" @click="getAddToCountHandler()()">

or

function getAddToCountHandler () {
    return function addToCount () {
        count + 1
    }()
}

let app=new Vue({
  el: "#app",
  data:function() {
    return {
      count: 0
    }
  },
  methods: {
   getAddToCountHandler() {
   let that=this;
      return function addToCount() {
      console.log(that.count)
        that.count =that.count+1
      }()
    }

  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="button" @click="getAddToCountHandler()" value="increment" /> {{count}}
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, Boussadjra, my question was incomplete. I've edited it to add context for you.
but what' the exact issue ?
Looking at the last script I added to my question, there is a closure with state I want to maintain throughout the lifespan of the click handler. Given your answer, that closure and handler is recreated, and the closure's state reset, each time the button is clicked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.