Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an Observer instead of my array?

My Vue Component consists of i.e. this code:

<script>
export default {
  data() {
    return {
      sailNames: []
    }
  },
  methods: {
    showName: function(e) { // [3] called by @click event from DOM
      console.log(this.sailNames); // [4] shows: [__ob__: Observer]
    },
    getJsonData() { // [1] called on created() hook
      $.getJSON("./src/res/sails.json", function(data) {
        const sailNames = [];
        $.each(data, function(i, names) {
          sailNames.push(names);
        });
        this.sailNames = sailNames;
        console.log(this.sailNames);
        console.log(sailNames); // [2] both logs give the same output
      });
    }
  }
}
(...)

I'm wondering, why I get this [__ob__: Observer] when logging the state at point [4]. As you see, the array is defined in the data section, then it gets values from a local variable and check is made: both local and global variables are identical (point [2]).

Then, when a user clicks on an element with showName method assigned (pt. [3]), I'd expect to see the same output as in pt. [2], but instead that [__ob__: Observer] appears in the console.

What is happening there? How should I call the array to get its values?

like image 232
AbreQueVoy Avatar asked Jun 13 '17 21:06

AbreQueVoy


1 Answers

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. Try to replace function expression with arrow functions.

<script>
export default {
  data() {
    return {
      sailNames: []
    }
  },
  methods: {
    showName(e){  
      console.log(this.sailNames); 
    },
    getJsonData() { 
      $.getJSON("./src/res/sails.json", (data) => {
        const sailNames = [];
        $.each(data, function(i, names) {
          sailNames.push(names);
        });
        this.sailNames = sailNames;
      });
    }
  }
}
</script>
like image 97
Sajed Avatar answered Oct 05 '22 04:10

Sajed