Setting dynamic css-style properties of a Backbone.View

Sean Anderson picture Sean Anderson · Aug 23, 2013 · Viewed 11.7k times · Source

I'm trying to set the height, width and background image of a <ul> element.

Here's what I've got for my Backbone.View:

var RackView = Backbone.View.extend({

    tagName: 'ul',

    className: 'rack unselectable',

    template: _.template($('#RackTemplate').html()),

    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },

    attributes: function () {
        var isFront = this.model.get('isFront');
        var imageUrlIndex = isFront ? 0 : 1;

        return {
            'background-image': 'url(' + this.model.get('imageUrls')[imageUrlIndex] + ')',
            'height': this.model.get('rows') + 'px',
            'width': this.model.get('width') + 'px'
        };
    }
}

This doesn't work because the attributes are not written into a 'style' property of the element. Instead, they're treated like attributes... which makes sense because of the function name, but it has left me wondering -- how do I achieve something like this properly?

The image, height and width are immutable after being set, if that helps simplify...

Do I just wrap my return in a style? That seems overly convoluted...

Here's the generated HTML:

<ul background-image="url(data:image/png;base64,...)" height="840px" width="240px" class="rack unselectable">
</ul>

EDIT: This works, but I'm not stoked:

attributes: function () {

    var isFront = this.model.get('isFront');
    var imageUrlIndex = isFront ? 0 : 1;

    var backgroundImageStyleProperty = "background-image: url(" + this.model.get('imageUrls')[imageUrlIndex] + ");";
    var heightStyleProperty = "height: " + this.model.get('rows') + 'px;';
    var widthStyleProperty = "width: " + this.model.get('width') + 'px;';

    return {
        'style': backgroundImageStyleProperty + ' ' + heightStyleProperty + ' ' + widthStyleProperty
    };
},

Answer

cclerv picture cclerv · Mar 31, 2014

You could just use the jquery css function in your render function:

render: function () {
    this.$el.html(this.template(this.model.toJSON()));
    var backgroundImageStyleProperty = "background-image: url(" + this.model.get('imageUrls')[imageUrlIndex] + ");";
    var heightStyleProperty = "height: " + this.model.get('rows') + 'px;';
    var widthStyleProperty = "width: " + this.model.get('width') + 'px;';

    this.$el.css({
     'height'          : heightStyleProperty,
     'width'           : widthStyleProperty,
     'background-image': backgroundImageStyleProperty
    });

    return this;
},