什么是对模型的字段进行一些预处理的好方法。例如,假设我有以下数据:
[{
id: '1',
sender: 'me',
receiver: 'you',
message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum",
date: new Date("October 13, 1975 11:13:00").toLocaleDateString()
}]
在这个简单的模型中:
App.Models.Notification = Backbone.Model.extend({
defaults: {
'date': new Date()
}
});
我想减少值中的字符数message
以便在视图中显示它,但前提是该消息包含超过给定数量的字符。也许是这样的:
if ( this.model.get('message').trim().split(" ").length > 30 ) {
// code here
}
因此,我不想在所有模型中执行该预处理。在我看来我应该这样做吗?如果是这样,怎么做?我已经阅读了一些解决方案,但其中一些不适用于这种情况,而另一些则看起来像是 hack。
谢谢!
更新
遵循 Alex 的建议并作为参考,我在这里举了一个使用 Handlebars 模板助手的示例:
render: function() {
Handlebars.registerHelper('getShort', function(options) {
if ( options.fn(this).trim().split(" ").length > 30 ) {
var message = options.fn(this);
var shortText = $('<div/>', { text: message })
.html()
.trim()
.substring(0, 200)
.split(" ")
.slice(0, -1)
.join(" ") + "..."
return shortText;
}
return options.fn(this);
});
template = Handlebars.compile( $("#my-template").html() );
this.$el.html( template( this.model.toJSON() ));
return this;
}
并像这样使用它:
索引.html
{{#getShort}}{{message}}{{/getShort}}