需要我自己的模块 [英] Requiring My Own Modules

查看:49
本文介绍了需要我自己的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究隔离DOM模式的概念证明,并且正在使用Browserify作为资产管道。结果,我在代码中需要它们时就需要模块。请参见以下非常简单的代码示例:

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

这是页面对象:

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

我不理解,无法找到返回为什么要实例化对象以使用它们的答案的搜索。我在Browserify GitHub和《手册》上找到的示例并没有显示这是必需的。但是,如果我没有在代码中更新这样的对象,则找不到模块...我想知道为什么。我可以对代码进行更改而不必这样做吗?

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


推荐答案

此刻,您导出了一个函数它返回一个对象。要检索该对象,必须首先执行导出的功能。如果只需要对象而不先执行函数,则只需导出对象而不是函数即可:

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

这篇关于需要我自己的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆