EmberJS 在组件中包装内容
在组件中包装内容
您还可以定义一个组件,帮助封装其他模板提供的内容,并将属性传递给另一个模板。该组件还支持块形式,并且在模板中以#符号为前缀。
<script type="text/x-handlebars">
//component name
{{my-comp title=title body=body}}
</script>
<script type="text/x-handlebars" data-template-name="components/my-comp">
// This is the component
{{title}} {{body}}
</script>
在上面的代码中,我们将 title 和 body 属性传递给另一个模板。
例子
<!DOCTYPE html>
<html>
<head>
<title>Emberjs Wrapping Content in a Component</title>
<!-- CDN's-->
<script src="/attachements/w3c/handlebars.min.js"></script>
<script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
<script src="/attachements/w3c/ember.min.js"></script>
<script src="/attachements/w3c/ember-template-compiler.js"></script>
<script src="/attachements/w3c/ember.debug.js"></script>
<script src="/attachements/w3c/ember-data.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="index">
<b>Click the button to check title property value</b>
<p>{{my-comp title=title action="compFunc"}}</p>
</script>
<script type="text/x-handlebars" data-template-name="components/my-comp">
<input type="button" value="Click me" {{action "compFunc"}} /><br/>
<!-- wrapping the 'title' property value -->
<p><b>Title:</b> {{title}}</p>
</script>
<script type="text/javascript">
App = Ember.Application.create();
App.MyCompComponent = Ember.Component.extend({
//defining the action hook to set the title property value
actions: {
compFunc: function() {
this.set('title', "Tutorialspoint...");
//This method sends the specified action
this.sendAction();
}
}
});
</script>
</body>
</html>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上面的代码保存在 comp_wrap.html 文件中
在浏览器中打开此HTML文件。