Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Listening for events only after a part of the script has ran

Hello, I was wondering how could I listen for events only after a specific part of the script has run.

This is my thought of how to do it, but I'm not quite sure how to type it.

// start
let client;

// click button and sign in
click () {
    client = someApp(username, password);
}

// NOW listen for events ONLY AFTER being logged in
client.addListener('blah', () => {});

// more events listeners and code

1 Answer

// login function
const login = (app, name, password) => {
  // you can do some other stuff here 
  // make app return true if the login was a success, otherwise return false
  return app(name, password)
}

const User = { } // to hold properties and event methods

// default variables
let client = false
let clientName = ''
let clientPassword = ''

// login the client and assign return value to client (true or false)
client = login(someApp, clientName, clientPassword)

// if client is true
if (client) {
  // then listen for event on the user
  User.addListener('blah', () => {})
}