EmberJS-Wrapping Content in a Component



Wrapping Content in a Component

You can also define a component that helps to wraps the contents provided by other templates and also pass the properties to another template. The component also support for block form and it is prefixed with # symbol in the template.

<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>

In the above code, we are passing the title and body properties to another template.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Wrapping Content in a Component</title>
      <!-- CDN's-->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/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>

Output

Let's carry out the following steps to see how above code works −

  • Save above code in comp_wrap.htm file

  • Open this HTML file in a browser.

Advertisements