Javascript 如何从模板访问属性?

Javascript 如何从模板访问属性?,javascript,canjs,canjs-component,Javascript,Canjs,Canjs Component,在这个例子中,我希望它说“helloworld”,但是这个世界不是从saying属性中提取出来的 (function () { 'use strict'; $(function () { // Set up a route that maps to the `filter` attribute can.route(':filter'); // Render #app-template $('#app').html

在这个例子中,我希望它说“helloworld”,但是这个世界不是从saying属性中提取出来的

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

你好
{{说}}。{{问候语}

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

can.Component.extend({
  tag: "app-say",
  scope: {
    saying: '@',
    greeting: 'salutations'
  },
  template: can.view("sayTemplate")
});
看。您最终可能想要做的是使用应用程序状态中的可观察属性,而不是普通的字符串值。这可能看起来像:

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>

你好

.

我的实际问题是我没有加载stache.js,但这有帮助。