简体   繁体   中英

Build javascript chain as text but execute as script

I'm working with this print library . What I'm trying to do now is build up my print payload. Right now when it's no dynamic it looks like this:

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

The issue I'm having is figuring out how to build up my print payload so that I can dynamcially create my string of .whatever().whatever().print() to actually do the printing.

I ran across this post and came up with the following code but get the error Uncaught ReferenceError: printLine is not defined which makes sense but I don't really know where to go from here.

So.....Basically what I'm asking is, what's a good way to build up a chained function call without it actually being executed as javascript until I trigger it?

 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> 

This is confusing, and seems a bit like an X/Y problem.

I think you want to just store the object in a variable, and then chain on another function at a later time

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

And looking at the plugin, it has a commandQueue where it stores all added commands, so you don't really have to store anything, each instance keeps track of the added commands automatically

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM