未捕获(承诺)TypeError:这是未定义的

时间:2020-10-25 11:19:41

标签: javascript model-view-controller promise async-await event-handling

当我在View Class中调用deleteCategory时,它给我一个错误。 在deleteCategory中调用del(event.target.id)时出错。 当我直接从View Class以这种方式调用它时,它就起作用了

       deleteCategory(service){
        this.tbody.addEventListener('click',async  event => {
            const clicked=event.target.tagName.toLowerCase();
            if (clicked == 'a'){
               const a= await this.service.deleteCategory(service.deleteCategory(event.target.id);
            }
        })
       }

是否可以使用View类中的事件处理程序在Controller类中调用deleteCategory?


class View{

    constructor(){
        this.e=document.createElement.bind(document);
        this.root=document.getElementById('root');
        this.tbody=document.querySelector('[table-items]');
    }
  
    categorylist(lists){ 
        
        lists.forEach((list) => {
        const tr=createTableRow(this.tbody,"");
        const td=createTableData(tr,list.name,"pl-4");
        const tdEditDelete=createTableData(tr,"","text-right pr-4");
        const editButton=createButton(tdEditDelete,'submit','Edit',list.id,'btn btn-primary mr-2');
        const deleteButton=createA(tdEditDelete,'Delete',list.id,'btn btn-danger');
        this.deleteButton=deleteButton;
        })  
    }



       deleteCategory(del){
        this.tbody.addEventListener('click',  event => {
            const clicked=event.target.tagName.toLowerCase();
            if (clicked == 'a'){     
                del(event.target.id);     
            }
        })
    }
}
class Controller{

    constructor(service,view){
        this.view=view;
        this.service=service;
        this.displayCategoryList();
        this.view.deleteCategory(this.deleteCategory);
        //this.deleteCategory();
    }

    async displayCategoryList() {
        const lists=await this.service.getLists();
        this.lists=lists;
        this.view.categorylist(lists);
    }
    
     async deleteCategory(id){
        //console.log(id);
        
        const a= await this.service.deleteCategory(id);
    }

}

1 个答案:

答案 0 :(得分:0)

我找到了这个解决方案并为我工作。

而不是在Controller类中调用deleteCategory构造函数

this.view.deleteCategory(this.deleteCategory);

用它代替

this.view.deleteCategory((async(id)=> {
     const a= await this.service.deleteCategory(id);
     }));