我尝试在SmartMobileStudio中使用htmlparser2模块(通过npm install htmlparser2
安装)。该模块本身适用于直接javascript(使用来自htmlparser2's Homepage的略微更改的样本):
var htmlparser = require("htmlparser2");
var parser = new htmlparser.Parser({
onopentag: function(name, attribs){
console.log(name);
console.log(attribs);
}
});
parser.write("<img src='image1.jpg'>");
parser.end();
使用SMS(2.0.0.9 Beta)我尝试导入这样的模块:
unit NodeJS.htmlparser2;
interface
uses
NodeJS.Core,
NodeJS.events;
type
TOnTag = procedure(name: string; attribs: Variant);
TOnText = procedure(text: string);
JParser = class external(NodeJS.events.JNodeEventEmitter)
procedure write(s: string);
procedure &end;
end;
Jhtmlparser_Exports = class external
public
function Parser(onopentag: TOnTag; ontext: TOnText; onclosetag: TOnTag): JParser;
end;
function htmlparser2: Jhtmlparser_Exports;
implementation
function htmlparser2: Jhtmlparser_Exports;
begin
result := Jhtmlparser_Exports( require("htmlparser2") );
end;
end.
我更改了Node.js-New-Project-Template生成的项目,如下所示:
[...]
procedure TServer.Run;
begin
var htmlparser := NodeJS.htmlparser2.htmlparser2;
var parser := htmlparser.Parser(
procedure (Name: string; Attribs: Variant)
begin
console_.log([Name]);
console_.log([Attribs]);
end,
nil,
nil);
parser.write("<img src='image1.jpg'>");
parser.end();
end;
问题是发出的代码不正确,但差不多:
[...]
parser = htmlparser.Parser(function (Name$3, Attribs) {
console_().log([Name$3].slice());
console_().log([Attribs].slice());
},null,null);
[...]
这有效:
[...]
parser = new htmlparser.Parser({onopentag: function (Name$3, Attribs) {
console_().log([Name$3].slice());
console_().log([Attribs].slice());
}});
[...]
区别在于“new”关键字和命名事件回调“onopentag”。我需要编写什么来生成有效的js代码?
答案 0 :(得分:3)
因为课程不能导出&#34;导出&#34;在pascal中你可以使用javascript和requirejs / nodejs,我们需要使用外部类技巧:我们可以为外部类名设置一些代码。 其次,我们需要提供一个&#34;选项&#34;对象(更详细但需要类型安全)。
JParserOptions = class
onopentag : TOnTag;
ontext : TOnText;
onclosetag: TOnTag
end;
JParser = class external '(htmlparser2()).Parser' (NodeJS.events.JNodeEventEmitter)
constructor Create(options: JParserOptions);
procedure write(s: string);
procedure &end;
end;
我们可以使用如下:
var options = JParserOptions.Create;
options.onopentag := procedure (Name: string; Attribs: Variant)
begin
console_.log([Name]);
console_.log([Attribs]);
end;
var parser := new JParser(options);
答案 1 :(得分:2)
顺便说一下,我找到了一个更好的解决方案:使用类引用(JParserClass = JParser类)
JParser = class external(NodeJS.events.JNodeEventEmitter)
constructor Create(onopentag: TOnTag; ontext: TOnText; onclosetag: TOnTag);
procedure write(s: string);
procedure &end;
end;
JParserClass = class of JParser;
Jhtmlparser_Exports = class external
public
Parser: JParserClass;
end;
然后你可以像这样创建类:
var parser := new (htmlparser2.Parser)(
或者像这样:
var parserclass = htmlparser2.Parser;
var parser := new parserclass(
或者:
var parserclass = htmlparser2.Parser;
var parser := parserclass.Create(