浏览器和文件准备好了吗? [英] browserify and document ready?

查看:83
本文介绍了浏览器和文件准备好了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用 Browserify 文件准备好事件。如何创建一个模块,用于导出仅在文档就绪事件触发后可用的内容?我如何依赖这样的模块?

I'm struggling with using Browserify and document ready events. How do I craft a module that exports content only available after the document ready event has fired? How do I depend on such a module?

我的第一个尝试是尝试异步设置module.exports - 开箱即用。我的下一个问题就是模块返回一个接受回调的函数,并在文件准备好时触发调用。第三次尝试回复了承诺。这似乎使依赖模块不是非常模块化,因为现在依赖模块及其依赖(以及他们的乌龟一直向下)也必须利用这种模式。

My first stab was to try to set module.exports asynchronously -- fail out of the box. My nextx stab at this was for the module to return a function that took in a callback, and called the callback when document ready fired. Third attempt returned a promise. This seems to make dependent modules not very modular as now dependent modules and their dependencies (and theirs, turtles all the way down) must also leverage this pattern.

什么是好的使用Browserify和文档就绪事件的模式?

What's a good pattern for using Browserify and document ready events?

推荐答案

试试这个:

var domready = require("domready");

domready(function () {
    exports.something = /* whatever you want */
});

您需要下载 domready 包:

npm install domready

然后只使用browserify:

Then just use browserify:

browserify input.js -o output.js

是的。就这么简单。

考虑到我们有两个文件: library.js main.js

Consider that we have two files: library.js and main.js.

// library.js

var domready = require("domready");

domready(function () {
    exports.test = "Hello World!";
});

// main.js

var library = require("./library");
var domready = require("domready");

domready(function () {
    alert(library.test);
});

只要您在注册主要domready功能之前需要图书馆,您应该可以使用库无缝地。

As long as you require your library before you register your main domready function you should be able to use your library seamlessly.

有时您可能希望设置 module.exports 到一个功能。在这种情况下,您可以使用以下hack:

Sometimes you may wish to set module.exports to a function. In that case you can use the following hack:

// library.js

var domready = require("domready");

module.exports = function () {
    return exports._call.apply(this, arguments);
};

domready(function () {
    exports._call = function () {
        alert("Hello World!");
    };
});

// main.js

var library = require("./library");
var domready = require("domready");

domready(function () {
    library();
});

请注意 _call 属性不在任何特别的方式。

Note that the _call property is not in any way special.

这篇关于浏览器和文件准备好了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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