0

I'm trying to update a data variable using Vue 2.x with the contents of an event emitter? (not sure if that's the correct term).

Example:

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      this.output = '';

      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         this.output += data.toString();
      });
    }
  }
}
</script>

How would I get the data variable to update inside that .on event?

Thanks!

François Maturel
  • 5,884
  • 6
  • 45
  • 50

2 Answers2

0

Use the fat arrow to preserve the context of this

myProcess.stdout.on('data', (data) => {
   this.output += data.toString()
})

Or you can use .bind()

myProcess.stdout.on('data', function(data) {

}.bind(this))

You can read more about arrow functions on the MDN

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
0

Without testing i would suggest these 2 Possibilities:

Bind this

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      this.output = '';

      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         this.output += data.toString();
      }.bind(this)); // now the outer this context (including output) is available
    }
  }
}
</script>

Or use function scope

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      var outputReference = this.output; // This should work because output is an observerObject and so only the pointer should be stored; not quite sure right now...


      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         outputReference += data.toString();
      });
    }
  }
}
</script>

I hope i got this right. Good luck

Thomas
  • 2,431
  • 17
  • 22