我试着调用一个我知道存在于变量上的函数但由于某种原因我无法从传递的函数onUpdate
中调用 - 任何想法的人 - 抱歉新手
//set up the mirror when view is expanded
function attachMirrorListener(section, mirror) {
var textarea = document.getElementById(mirror.attr('id'));
var input = $(mirror.data('input'));
var myCodeMirror;
section.click(function() {
if(section.hasClass('open') && !section.hasClass('mirror-added')) {
section.addClass('mirror-added');
input.attr('value','test value!!');
myCodeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : function(){ myCodeMirror.save(); //does not work here!!
},
});
}
console.log(myCodeMirror);
myCodeMirror.save(); //works here
});
}
});
更新
我尝试重新排列代码,仍然无法正常工作
jQuery(document).ready(function($) {
var _codeMirror;
//setup code-mirror
$('.customize-section').each(function() {
var section = $(this);
var mirror = section.find('textarea.wpec-tc-code-mirror');
if(mirror.length > 0) {
attachMirrorListener(section, mirror);
}
});
//set up the mirror when view is expanded
function attachMirrorListener(section, mirror) {
var textarea = document.getElementById(mirror.attr('id'));
var input = $(mirror.data('input'));
section.click(function() {
if(section.hasClass('open') && !section.hasClass('mirror-added')) {
section.addClass('mirror-added');
_codeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : codemirrorcallback,
});
}
});
function codemirrorcallback() {
_codeMirror.save();
input.val(escape(textarea.value));
}
}
});
以下是Chrome控制台的错误日志
Uncaught TypeError: Cannot call method 'save' of undefined codemirror.js:26
codemirrorcallback codemirror.js:26
endOperation codemirror.js:1864
instance.(anonymous function) codemirror.js:1871
CodeMirror codemirror.js:95
CodeMirror.fromTextArea codemirror.js:2114
(anonymous function) codemirror.js:19
f.event.dispatch load-scripts.php:3
f.event.add.h.handle.i
答案 0 :(得分:0)
赋值运算符从右到左工作。因此,当您第一次调用myCodeMirror.save()
时,myCodeMirror
仍未定义。
var myCodeMirror; //undefined
myCodeMirror = CodeMirror.fromTextArea(textarea, {
onUpdate : function() {
myCodeMirror.save(); //still undefined
}
});
您应该在内部onUpdate函数中调用this.save()
。