CanJS模型的动态属性?

时间:2012-09-16 13:14:42

标签: javascript javascript-framework canjs canjs-model

我想在我的模型中添加不在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>
<% } %>

注意我在模板中为图像src和开始/结束日期做的逻辑。我想把这个逻辑放在模型中,所以我在模板中所要做的就是:

<% 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>
<% } %>

如何将此逻辑移动到模型层或模板中更好的位置?感谢您的帮助或建议。

1 个答案:

答案 0 :(得分: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>
<% } %>