Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting dynamic css-style properties of a Backbone.View

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
    };
},
like image 996
Sean Anderson Avatar asked Aug 22 '13 22:08

Sean Anderson


2 Answers

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;
},
like image 187
cclerv Avatar answered Sep 21 '22 22:09

cclerv


In Marionette, right in your view you can call:

onRender: function () {
  this.$('yourElement').css('whatever', 'css');
},
like image 38
Cesar Martinez Dominguez Avatar answered Sep 17 '22 22:09

Cesar Martinez Dominguez