0

次のテンプレートとモデルを ractive で使用して、firebase を使用した簡単なテスト アプリケーションを作成しました。計算された newprice の価格値にアクセスして、小数点以下 2 桁の通貨のように書式設定したいと考えています。出力に問題なく表示される .price 値を取得する方法はわかりませんが、計算された内部で .price を表示できるように試したことはありません。newprice の呼び出しは、テキストを返すだけで出力に表示されるため、正常に機能します。.price を使用している理由は、firebase から返されたデータには、一意の自動生成 ID でラップされた各 make、model、price があるため、各エントリ ID を持つトップ レベル オブジェクトとその中のデータが make、model、価格。

<script id='template' type='text/ractive'>
{{#each listdata:i}}
    <p>{{ .make }} {{ .model }}{{.price}} ${{ newprice() }}!</p>
{{/each}}
</script>
<script>
    var ractive = new Ractive({
      // The `el` option can be a node, an ID, or a CSS selector.
      el: 'container',

      // We could pass in a string, but for the sake of convenience
      // we're passing the ID of the <script> tag above.
      template: '#template',
      computed: {
        newprice: function() {
          // CAN'T FIGURE OUT WHAT TO DO HERE TO SEE price
          return  ;
        }
      }
    });

</script>

.price 値を取得する方法についての指示が必要です。

4

2 に答える 2

2

計算されたプロパティは、関数ではなくプロパティとして参照されます。さらに重要なことは、「絶対」キーパスであるため、コレクションに対して機能しません。これを機能させるには、次の 2 つのオプションがあります。

データ関数を使用する

計算されたプロパティの代わりに、データ関数を使用します。

<script id='template' type='text/ractive'>
{{#each listdata:i}}
    <p>{{ .make }} {{ .model }}{{.price}} ${{ newprice(.price) }}!</p>
{{/each}}
</script>
<script>
    var ractive = new Ractive({
      el: 'container',
      template: '#template',
      data: {
        newprice: function(price) {
          return price + 1;
        },
        // other data
      }
    });

</script>

ヘルパー関数を「グローバル」に配置する方が便利な場合があります。

Ractive.defaults.data.newprice = function(price){...}

既存の/お気に入りのライブラリがある場合は、この手法を使用して、テンプレート内でメソッドにインラインでアクセスすることもできます

<script src="path/to/accounting.js"></script>
Ractive.defaults.data.accounting = accounting

<p>{{ .make }} {{ .model }}{{.price}} ${{ accounting.formatMoney(.price) }}!</p>

計算されたプロパティを使用しますが、コンポーネント レベルで使用します

コンポーネントを使用して各アイテムをレンダリングすると、計算されたプロパティはアイテムごとになります。

<script id='template' type='text/ractive'>
{{#each listdata:i}}
    <line/>
{{/each}}
</script>

<script id='line' type='text/ractive'>
    <p>{{ make }} {{ model }}{{price}} ${{ newprice }}!</p>
</script>

<script>
    Ractive.components.line = Ractive.extend({
      template: '#line',
      computed : {
        newprice: function(){
           return this.get('price')
        }
      }
    })
    var ractive = new Ractive({
      el: 'container',
      template: '#template',
    });

</script>
于 2014-08-30T15:03:30.603 に答える