如何从模板中访问属性?

时间:2014-09-09 11:20:59

标签: javascript canjs canjs-component

在这个例子中,我希望它能说出“你好世界”,但世界并没有从说法属性中汲取。

(function () {
    'use strict';

    $(function () {
        // Set up a route that maps to the `filter` attribute
        can.route(':filter');

        // Render #app-template
        $('#app').html(can.view('appTemplate', {}));

        // Start the router
        can.route.ready();
    });

    can.Component.extend({
        tag: "say",
        scope: {
            saying: function(){
                return this.attr('saying')
            },
            greeting: 'salutations'
        },
        template: can.view("sayTemplate")
    });

})();

模板:

<div id="app"></div>

<script id="appTemplate" type="text/mustache">
  <b>Hello</b>
  <say saying="world"></say>
</script>

<script id="sayTemplate" type="text/mustache">
    <b>{{saying}}.</b> <i>{{greeting}}</i>
</script>

1 个答案:

答案 0 :(得分:0)

您需要告诉组件您要访问属性普通值,如下所示:

can.Component.extend({
  tag: "app-say",
  scope: {
    saying: '@',
    greeting: 'salutations'
  },
  template: can.view("sayTemplate")
});

this Fiddle。您最终可能想要做的是使用应用程序状态中的可观察属性而不是纯字符串值。这可能看起来像:

var appState = new can.Map({
    name: 'World'
});

$(function () {
    // Set up a route that maps to the `filter` attribute
    can.route(':filter');

    // Render #app-template
    $('#app').html(can.view('appTemplate', appState));

    // Start the router
    can.route.ready();
});

can.Component.extend({
    tag: "app-say",
    scope: {
        greeting: 'salutations'
    },
    template: can.view("sayTemplate")
});

还有一个模板:

<div id="app"></div>

<script id="appTemplate" type="text/mustache">
  <b>Hello</b>
  <app-say saying="{name}"></app-say>
  <div><input type="text" can-value="name"></div>
</script>

<script id="sayTemplate" type="text/mustache">
    <b>{{saying}}.</b> <i>{{greeting}}</i>
</script>

这也会创建一个交叉绑定的输入字段,每当您更新文本字段时,该字段都会更新名称。小提琴是here