3 回答

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
我想用來自外部字符串的動(dòng)態(tài)參數(shù)實(shí)例化一個(gè)新對象。
這是代碼:
const editorInstance = new Editor('#edit',
{
placeholderText: null,
theme: 'dark',
language: 'en',
linkList:[{text: 'test',href: 'test',target: '_blank'}],
events: {
initialized: function () {
const editor = this
this.el.closest('form').addEventListener('submit', function (e) {
jQuery('#gs_editor_content').hide();
jQuery(this).append('<div class="loadingDiv"> </div>');
o.script
});
texta = jQuery('#myeditor').find('textarea');
targetFile = texta.attr('rel');
content = editor.$oel.val();
e.preventDefault();
var fd = new FormData();
fd.append( 'name' ,targetFile);
fd.append( 'html', editor.$oel.val() );
$.ajax({
url : 'http://localhost/Update',
type : 'POST',
data: fd,
processData : false,
contentType : false,
async : false,
success : function(data, textStatus, request) {}
});
jQuery('#myeditor').dialog("close");
}
}
}
)
linkList當(dāng)我收到從我的服務(wù)器收到的新列表時(shí),我需要在實(shí)例化我的對象之前修改參數(shù)。
我嘗試使用 eval 或 parseFunction,但遇到意外的標(biāo)識符錯(cuò)誤。
知道我怎么能做到這一點(diǎn)嗎?

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果我理解您的問題是正確的,您是否在將鏈接列表包含到新對象之前嘗試更新它?
如果是這種情況,您可以使用基于承諾的東西作為 fetch 來獲取您的數(shù)據(jù):Using Fetch by MDN documentation。您已經(jīng)在使用 JS 類,所以我確定您已經(jīng)了解瀏覽器兼容性或使用 Babel(如果瀏覽器兼容性對您很重要)。
如果您更喜歡使用 jQuery AJAX 來獲取數(shù)據(jù),您可以使用 async await 在您的軟件實(shí)例化對象之前更新 linkList。Async Await 的 MDN 文檔。
在這種情況下,您可以執(zhí)行以下操作:
async function getData(paramIfNeeded) {
var linkListData = await linkListFunction(paramIfNeeded2);
return linkListData
}
function linkListFunction(paramIfNeeded2){
//Your favourite data fetching function
}
getData().then((result) =>{
var linkList = result;
//instanciate the object
});
如果您更喜歡 ES 2015,可以這樣做:
function callData(){
getData(paramIfNeeded)
.then(result => {
linkListFunction(paramIfNeeded2)
.then( result => {
//do things with linkList
});
});
}

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
問題可能是由異步引起的。您的班級正在從您的服務(wù)器收到響應(yīng)之前初始化。您需要在收到響應(yīng)后初始化類。
例如
const editorInstance = new Editor("#edit", {
placeholderText: null,
theme: "dark",
language: "en",
linkList: serverExample() // undefined
});
function serverExample() {
setTimeout(() => {
return [
{ text: "test", href: "test", target: "_blank" },
{ text: "test2", href: "test", target: "_blank" }
];
}, 3000);
}
添加回答
舉報(bào)