What is a good way to do some preprocessing on fields of a model. For example, suppose I have this data:
[{
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()
}]
In this simple model:
App.Models.Notification = Backbone.Model.extend({
defaults: {
'date': new Date()
}
});
And I want to reduce the number of characters in the value of message in order to display it in a view, but only if that message contains more than a given number of characters. Maybe something like this:
if ( this.model.get('message').trim().split(" ").length > 30 ) {
// code here
}
So, I don’t want to perform that preprocessing in all models. Should I do it in my view? If so, how? I have read a few solutions but some of them don’t apply to this situation and others seem like a hack.
Thanks!
UPDATE
Following Alex’s suggestion and as a reference, I put here an example of using Handlebars’ template helpers:
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;
}
and using it like this:
index.html
{{#getShort}}{{message}}{{/getShort}}
This kind of presentation logic should be put in template helpers, if your library stack supports them. If not, just add
getShortenedMessage(length)method to model and use it to get your value. In any case, don’t change actual model attribute just to display it differently — this is bad design and can lead to all kinds of complications later.