codecamp

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文件。

温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }