Skip to content
This repository was archived by the owner on Apr 2, 2019. It is now read-only.
This repository was archived by the owner on Apr 2, 2019. It is now read-only.

No way to "pre-process" a value before formatting without overwriting render #263

@machineghost

Description

@machineghost

Backgrid's built-in cell system works great as long as the value stored in the model's attribute is exactly what you want to send to your formatter. But what do you do if you need to process that value somehow before you format it?

For instance, let's say you have a type of cell where the model's value is an ID of an object. To display the relevant details of that cell, you need to get the object. This could be as simple as:

var id = this.model.get(this.column.get("name"));
var value = someCollection.get(id);

or it could be more complicated:

var someCollection;
if (id.indexOf('foo') != -1) {
    someCollection = collectionA;
} else if (id.indexOf('bar') != -1) {
   someCollection = collectionB;
} else if ...

var value = someCollection.get(id);

You could do all that logic in the formatter function, but then if you want to have different formatters for different cells of this type, you have to repeat the code. Alternatively you could overwrite the render method, but since there's other stuff in the render method, you risk having a future version of Backgrid change the render method somehow and break your code.

All of this can be solved very simply by just separating out the value-grabbing logic of Backgrid.Cell.prototype.render in to one or two methods:

getValue: function() {
    return this.model.get(this.column.get("name"));
},
render: function() {
    this.$el.empty();
    this.$el.text(this.formatter.fromRaw(this.getValue()));
    ...

(which would allow people to override getValue to "pre-process" their values), or even better:

getRawValue: function() {
    return this.model.get(this.column.get("name"));
},
processValue: function(rawValue) {
    return rawValue;
}
render: function() {
    this.$el.empty();
    this.$el.text(this.formatter.fromRaw(this.processValue(this.getRawValue())));
    ...

(which would let people override processValue without having to repeat the getRawValue logic).

Either one of these changes would allow a lot more flexibility in controlling the output of a Backgrid cell, would require almost no effort at all to implement, and would have no effect on any existing Backgrid code. Would it be possible to make one of the two part of Backgrid?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions