EmberJS 定义组件
定义组件
通过创建名称以 components/ 开头的模板,很容易在Ember.js中定义组件。组件的名称(my-name)中必须有短划线。Ember.js有能力通过使用一个Ember.Component 类来定义组件子类。
<script type="text/x-handlebars">
//component name
{{my-comp}}
</script>
<script type="text/x-handlebars" data-template-name="components/my-comp">
// This is component
</script>
Ember.Component.extend({ //do the stuff });
在上述代码中,my-comp 是在下一个脚本标记中声明为 components / my-comp 的组件。您还可以扩展 Ember.Component 类以获得更多效果。
例子
<!DOCTYPE html>
<html>
<head>
<title>Emberjs Defining 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">
<h2>Defining Component</h2>
<p><b>Name:</b>{{name}}</p>
<!-- defining the component 'my-comp' with 'myvalue' property -->
{{my-comp myvalue=name}}
</script>
<script type="text/x-handlebars" data-template-name="components/my-comp">
<input type="button" value="Click me" {{action "compFunc"}}/>
<b>{{myvalue}}</b>
</script>
<script type="text/javascript">
App = Ember.Application.create();
App.IndexRoute = Ember.Route.extend({
model: function(){
//initializing the 'name' property value as 'my data' and return the value
return {name: 'my data'};
}
});
App.MyCompComponent = Ember.Component.extend({
actions: {
compFunc: function() {
//setting up the new value for 'myvalue' property as 'Tutorialspoint'
this.set('myvalue', "Tutorialspoint");
//This method sends the specified action when the component is used in a template
this.sendAction();
}
}
});
</script>
</body>
</html>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上述代码保存在 define_component.html 文件中
在浏览器中打开此HTML文件。