Search code examples
javascriptbrowserify

Requiring My Own Modules


I am working up a proof of concept for the Segregated DOM pattern and am using Browserify as my asset pipeline. As a result I am "requiring" modules as I need them in the code. Please see this very simple code example:

var loginForm = require('page-objects/loginForm');

lf = loginForm();

lf.signInButton.on('click', function(event){
    event.preventDefault();
    lf.email.val('TEST')
})

and here is the page object:

module.exports = LoginForm;

function LoginForm(){
    var $ = require('jQuery'),
    navbarForm = $('form.navbar-form');

    return {
        email: navbarForm.find('input[placeholder="Email"]'),
        password: navbarForm.find('input[placeholder="Password"]'),
        signInButton: navbarForm.find(':button')
    }
}

I do not understand and cannot find a search that returns an answer as to why I need to instantiate the objects to use them. The examples I found on the Browserify GitHub and the Handbook do not show that as a requirement. However if I do not "new up" an object like this in my code the module is not found...I would like to know why that is. Are there changes I can make to my code to NOT have to do this?

Code without the object instantiation:

var loginForm = require('page-objects/loginForm');

loginForm.signInButton.on('click', function(event){
    event.preventDefault();
    loginForm .email.val('TEST')
})

Solution

  • At this moment, you export a function which returns an object. To retrieve the object, you have to execute the exported function first. If you just want the object without first executing a function, just export the object instead of a function:

    var $ = require('jQuery'),
    var navbarForm = $('form.navbar-form');
    
    module.exports = {
        email: navbarForm.find('input[placeholder="Email"]'),
        password: navbarForm.find('input[placeholder="Password"]'),
        signInButton: navbarForm.find(':button')
    }