Requiring My Own Modules

点点圈 提交于 2020-01-04 05:27:31

问题


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')
})

回答1:


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')
}


来源:https://stackoverflow.com/questions/45417445/requiring-my-own-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!