0

REST サービスの結果にない動的プロパティをモデルに追加したいと考えています。これらの動的プロパティは、名前の短縮、日付の書式設定などを行います。たとえば、私の CanJS モデルは次のようになります。

var MyModel = can.Model({
    findAll: 'GET /Services/all'),
    findOne: 'GET /Services/{id}'),
    create:  'POST /Services/all'),
    update:  'PUT /Services/{id}'),
    destroy: 'DELETE /Services/{id}')
}, {});

次に、次のようにデータを取得します。

MyModel.findAll({}, function(data) {
    $('#main').html(can.view('templates/List.ejs'), data));
});

そして、これは私の List.ejs テンプレートがどのように見えるかです:

<% for(var i = 0; i < this.length; i++) { %>
    <div class="thumb"><img src="http://cdn.somewhere.com/images/logo.<%= this[i].BaseName %>.png" /></div>
    <div class="title"><%= this[i].Name %></div>
    <div class="date"><%= moment(this[i].StartDate).format('MMM DD, YYYY') %> - <%= moment(this[i].EndDate).format('MMM DD, YYYY') %></div>
    <div class="location"><%= this[i].LocationFriendly %></div>
    <div class="description"><%= this[i].Description %></div>
<% } %>

画像のソースと開始日/終了日のテンプレートで実行しているロジックに注目してください。このロジックをモデルに入れたいので、テンプレートで行う必要があるのは次のとおりです。

<% for(var i = 0; i < this.length; i++) { %>
    <div class="thumb"><img src="<%= this[i].ImageURL %>" /></div>
    <div class="title"><%= this[i].Name %></div>
    <div class="date"><%= this[i].StartDateFriendly %> - <%= this[i].EndDateFriendly %></div>
    <div class="location"><%= this[i].LocationFriendly %></div>
    <div class="description"><%= this[i].Description %></div>
<% } %>

このロジックをモデルレイヤーまたはテンプレートよりも適切な場所に移動するにはどうすればよいですか? 助けやアドバイスをありがとう。

4

1 に答える 1

3

最も簡単な方法は、モデルに関数を作成することです。

var MyModel = can.Model({
    findAll: 'GET /Services/all',
    findOne: 'GET /Services/{id}',
    create:  'POST /Services/all',
    update:  'PUT /Services/{id}',
    destroy: 'DELETE /Services/{id}'
}, {
    imageUrl : function(){
        return "http://cdn.location.com/" + this.BaseName + ".png"
    },
    startDateFriendly : function(){
        return moment(this.StartDate).format('MMM DD, YYYY')
    },
    endDateFriendly : function(){
        return moment(this.StartDate).format('MMM DD, YYYY')
    },
    locationFriendly: function() {
        // ...
    }
});

次に、ビューからこれらの関数を呼び出すことができます。

<% for(var i = 0; i < this.length; i++) { %>
    <div class="thumb"><img src="<%= this[i].imageUrl() %>" /></div>
    <div class="title"><%= this[i].Name %></div>
    <div class="date"><%= this[i].startDateFriendly() %> - <%= this[i].endDateFriendly() %></div>
    <div class="location"><%= this[i].locationFriendly %></div>
    <div class="description"><%= this[i].Description %></div>
<% } %>
于 2012-09-17T07:38:05.317 に答える