我正在与 this print library 合作。我现在想做的是构建我的 print
有效负载。现在,当它没有动态时,它看起来像这样:
serialPort.on('open',function() {
var printer = new Printer(serialPort);
printer.on('ready', function() {
printer
.printLine('text line 1')
.printLine('text line 2')
.printLine('text line 3')
.print(function() {
console.log('done');
//do other stuff
});
});
});
我遇到的问题是弄清楚如何构建我的打印有效负载,以便我可以动态创建 .whatever().whatever().print() 字符串
实际进行打印。
我遇到了this post并提出了以下代码,但收到错误 Uncaught ReferenceError: printLine is not Defined
这是有道理的,但我真的不知道从这里去哪里。
所以......基本上我要问的是,什么是建立链式函数调用的好方法,而不需要在我触发它之前将其实际作为 JavaScript 执行?
var buildLine = Function("input", "printLine('input')");
var lineItems = ['hello', 'world'];
var printPayload = '';
_.map(lineItems, function(item) {
printPayload += buildLine(item)
})
console.log(printPayload);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
最佳答案
这很令人困惑,看起来有点像 X/Y 问题。
我认为您只想将对象存储在变量中,然后稍后链接到另一个函数
serialPort.on('open', function() {
var printer = new Printer(serialPort),
intance;
printer.on('ready', function() {
intance = printer.printLine('text line 1')
.printLine('text line 2')
.printLine('text line 3');
});
something.on('later_event', function() {
instance.print(function() {
// done
});
});
});
查看该插件,它有一个 commandQueue
,其中存储所有添加的命令,因此您实际上不必存储任何内容,每个实例都会自动跟踪添加的命令
serialPort.on('open', function() {
var printer = new Printer(serialPort);
var lineItems = ['hello', 'world'];
printer.on('ready', function() {
lineItems.forEach(function(line) {
printer.printLine(line);
});
});
something.on('later_event', function() {
printer.print(function() {
// done
});
});
});
关于javascript - 将 javascript 链构建为文本但作为脚本执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581484/