通過創(chuàng)建名稱以 components/ 開頭的模板,很容易在Ember.js中定義組件。組件的名稱(my-name)中必須有短劃線。Ember.js有能力通過使用一個(gè)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 是在下一個(gè)腳本標(biāo)記中聲明為 components / my-comp 的組件。您還可以擴(kuò)展 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>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上述代碼保存在 define_component.html 文件中
在瀏覽器中打開此HTML文件。
更多建議: