Z
Z
zyusifov112022-03-02 16:13:36
1C-Bitrix
zyusifov11, 2022-03-02 16:13:36

How to call a function from methods in created?

export default {
    name: 'App',
    data(){
      return {
        messages: [],
        newMessage: null,
        connection: null
      };
    },
    created: function() {
      this.connection = new WebSocket("ws://127.0.0.1:8000/ws/chat/")

      this.connection.onmessage = function(event) {
        let receivedMessage = JSON.parse(event.data).message;
        this.receiveMessage(receivedMessage)
      }
      this.connection.onopen = function(event) {
        return event
      }

    },
    methods: {
      sendMessage: function () {
        this.connection.send('{"message":"'+this.newMessage+'"}');
      },
      receiveMessage(message) {
        this.messages.push(message)
      }
    }
  }

error:
this.receiveMessage is not a function

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Defman21, 2016-04-16
@Defman21

jQuery(document).ready(function($){alert("I work");});

I
Ilya, 2022-03-03
@zyusifov11

Try like this:

created () {
      this.connection = new WebSocket("ws://127.0.0.1:8000/ws/chat/")

      this.connection.onmessage = event => {
        let receivedMessage = JSON.parse(event.data).message;
        this.receiveMessage(receivedMessage)
      }
      this.connection.onopen = function(event) {
        return event
      }

    },

I changed the code to be an arrow function, `this` in this function will point to the desired context (of the created method). I also changed it to a shorter form
this.connection.onmessage = event => {
created: function() {created () {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question