3 回答

TA貢獻1993條經驗 獲得超6個贊
我想用來自外部字符串的動態參數實例化一個新對象。
這是代碼:
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當我收到從我的服務器收到的新列表時,我需要在實例化我的對象之前修改參數。
我嘗試使用 eval 或 parseFunction,但遇到意外的標識符錯誤。
知道我怎么能做到這一點嗎?

TA貢獻1829條經驗 獲得超7個贊
如果我理解您的問題是正確的,您是否在將鏈接列表包含到新對象之前嘗試更新它?
如果是這種情況,您可以使用基于承諾的東西作為 fetch 來獲取您的數據:Using Fetch by MDN documentation。您已經在使用 JS 類,所以我確定您已經了解瀏覽器兼容性或使用 Babel(如果瀏覽器兼容性對您很重要)。
如果您更喜歡使用 jQuery AJAX 來獲取數據,您可以使用 async await 在您的軟件實例化對象之前更新 linkList。Async Await 的 MDN 文檔。
在這種情況下,您可以執行以下操作:
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貢獻1868條經驗 獲得超4個贊
問題可能是由異步引起的。您的班級正在從您的服務器收到響應之前初始化。您需要在收到響應后初始化類。
例如
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);
}
添加回答
舉報