0

I have a function publicRooms to display public discussions that are on the server. I want to use this data for another function I created addNewMessageNewThread:

matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});

Off when I do that, he tells me he does not know this function :

ERROR TypeError: Cannot read property 'addNewMessageNewThread' of undefined

And when I test this function outside the function, it works

///////////EDIT//////////////

This is my function addNewMessageNewThread() :

addNewMessageNewThread(objMessage: any): void {

    const newUser: User      = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [newUser],objMessage.title);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.arrayMessages.push(newMessage);
    newThread.messages = Observable.of(newThread.arrayMessages);

    newThread.lastMessage = newMessage;

    objMessage.thread = newThread;
    this.addThread(newThread);
}
1
  • What does addNewMessageNewThread() do? Is it by any chance asynchronous? Commented Nov 16, 2017 at 10:10

2 Answers 2

4

You should pass the context this:

matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
}, this); 

Or use arrow function to use the parent context:

matrixClient.publicRooms((err, data) => {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
}); 
Sign up to request clarification or add additional context in comments.

Comments

0

Instrad of calling this.addNewMessageNewThread try with matrixClient.addNewMessageNewThread.

this reffers to the callback's context.

If this addNewMessageNewThread doesn't belong to the matrixClient (guessing), before calling matrixClient.publicRooms(), assing:

var that = this;

And use that inside callback instead of this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.