1.增加代码编辑的div块
效果是这样的:
2.在defaults中加入func内容
再加入一个隐藏的input域
注意其id刚好与defaults中的func匹配
这样我们就能将这个隐藏的input中的内容传到后台了,我们只需要将文本编辑框内的信息填到这个input中即可
3.加一个oneditprepare函数,修饰1中代码输入框div的样式,并将这个隐藏的input与代码输入框相关联
oneditprepare: function() {
this.editor = RED.editor.createEditor({
id: 'node-input-func-editor', //代码输入框
mode: 'ace/mode/javascript', //代码模式为js
value: $("#node-input-func").val(),//值与func绑定
});
},
4.当点击完成后把代码输入框内的内容进行储存,用oneditsave函数,记得最后销毁由oneditprepare创造出来的editor对象
oneditsave: function() {
$("#node-input-func").val(this.editor.getValue());
this.editor.destroy();
delete this.editor;
},
5.如果点取消
如果取消,就直接销毁editor对象就好
oneditcancel: function() {
this.editor.destroy();
delete this.editor;
},
6.在后台这样写,注意this.on,每次有数据input进来,就会运行一次console.log(this.n.func)
module.exports = function(RED) {
"use strict";
function SampleNode(n) {
RED.nodes.createNode(this,n);
var msg = {};
this.n=n
this.on('input', function (msg) {
console.log(this.n.func)
node.send(msg);
});
this.on("close", function() {
});
}
RED.nodes.registerType("sample",SampleNode);
}
效果如下:
7.将代码编辑框里打的代码用debug块显示
到目前为止,如果加一个debug,会报错
所以这个问题只要将后端代码加一句var node=this 就好。
以下是sample.js的全部代码
module.exports = function(RED) {
"use strict";
var vm = require("vm");
function SampleNode(n) {
RED.nodes.createNode(this,n);
var node = this;
this.on('input', function (msg) {
msg.payload=n.func
console.log(n)
node.send(msg);
});
this.on("close", function() {
});
}
RED.nodes.registerType("sample",SampleNode);
}
顺便贴上sample.html的全部代码
<script type="text/x-red" data-template-name="sample">
<div class="form-row" style="margin-bottom: 0px;">
<label for="node-input-func"><i class="fa fa-wrench"></i> <span data-i18n="function.label.function"></span></label>
<input type="hidden" id="node-input-func" autofocus="autofocus">
</div>
<div class="form-row node-text-editor-row">
<div style="height: 250px; min-height:150px;" class="node-text-editor" id="node-input-func-editor" ></div>
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('sample',{
category: 'input', // the palette category
defaults: { // defines the editable properties of the node
func: {value:"\nreturn msg;"},
},
inputs:1, // set the number of inputs - only 0 or 1
outputs:1, // set the number of outputs - 0 to n
// set the icon (held in icons dir below where you save the node)
icon: "myicon.png", // saved in icons/myicon.png
label: function() { // sets the default label contents
return this.name||this.topic||"sample";
},
labelStyle: function() { // sets the class to apply to the label
return this.name?"node_label_italic":"";
},
oneditprepare: function() {
this.editor = RED.editor.createEditor({
id: 'node-input-func-editor',
mode: 'ace/mode/javascript',
value: $("#node-input-func").val(),
});
},
oneditsave: function() {
$("#node-input-func").val(this.editor.getValue());
this.editor.destroy();
delete this.editor;
},
oneditcancel: function() {
this.editor.destroy();
delete this.editor;
},
});
</script>