如何从ember.js中的hbs文件中调用js函数



这是ember.js 中的主要应用程序

app/templates/application.hbs

{{page-title "User Management"}}
<ul>
<LinkTo @route="print-user" >Print User</LinkTo>
</ul>
{{outlet}}

这是从servlet 获取json数组响应的代码

app/components/print-user.js

import Component from '@glimmer/component';
import {action} from "@ember/object";
import {tracked} from "@glimmer/tracking";
export default class PrintUserComponent extends Component {
@tracked search="";
@tracked print="";
@tracked gotresponse=false;
@action 
async searchuser (searchtext){
let response=await fetch("/UserManagement/SearchServlet",
{   method: "POST",
body: JSON.stringify({
"type": "search",
"searchtext": searchtext
})
});
let parsed=await response.json();
this.gotresponse=true;
this.search=parsed;
}
async deleteuser (id,firstname,lastname,mailid){
let response=await fetch("/UserManagement/UserManagementServlet",
{   method: "POST",
body: JSON.stringify({
"type": "delete",
"id": id,
"firstname":firstname,
"lastname":lastname,
"mailid":mailid
})
});
let parsed=await response.json();
alert(parsed.status);
}
}

这是在网页中打印用户表的hbs代码

app/components/print-user.hbs


<input5>{{input type="text" value=search placeholder="Enter Text"}}</input5>
<searchbutton {{on "click" (fn this.searchuser search )}}>Search</searchbutton>
<table class="styled-table">
<thead>
<tr><th>User Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Mailid</th>
<th>Delete</th>
</tr>
</thead>
{{#each this.search.Users_data as |user|}}
<tbody>
<tr>
<td>{{user.id}}</td>
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td>{{user.mailid}}</td>
<td><button {{on "click" (fn deleteuser user.id user.firstname user.lastname user.mailid )}}>Delete</button></td>
</tr>
</tbody>
{{/each}}
</table>
{{yield}}

在应用程序中单击打印用户时,我需要打印用户数据。bbs当我点击搜索按钮时,它工作正常。我不知道如何在不点击按钮的情况下打印用户详细信息。。。。

您可以从constructor:手动调用searchuser操作

constructor() {
super(...arguments);
this.searchuser('default search value');
}

显然,您想在组件上调用searchuser操作,而无需单击组件上的按钮,即显示组件时。为此使用did-insert修饰符。

通常情况是这样的:将修饰符放在组件中的标记上。在您的情况下,<input5>searchbutton即可。

<input5 {{did-insert this.searchuser}}>
{{input type="text" value=search placeholder="Enter Text"}}
</input5>
etc...

最新更新