2012-09-16 72 views
0

我想在我的模型中添加不在REST服务结果中的动态属性。这些动态特性将缩短名称,日期格式等。例如,我CanJS模式是这样的: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)); 
}); 

这该是多么我的列表。 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> 
<% } %> 

如何我提出这个逻辑到模型层或任何更好的地方,然后在模板?感谢您的任何帮助或建议。

回答

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

我刚试过,但模板给出了一个错误:未捕获TypeError:对象#没有方法'imageUrl'。我也尝试没有括号,但在模板上显示空白。你知道在prototypeSperties辅助方法的EJS模板中是否有特殊的事情要做? – Basem

+0

它切换到真正的REST服务而不是模拟的服务器后工作。谢谢! – Basem