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
    };
},

你可以在render函数中使用jQuery的css函数:

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;
},

在Marionette中,在你看来,你可以打电话给:

onRender: function () {
  this.$('yourElement').css('whatever', 'css');
},

The only way to do this is to pass in the attributes using a style attribute as described in the question. In backbone, the attribute map is passed directly into jQuery by this line of code:

var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);

So, there is no way to pass in styles as a Javascript object.

链接地址: http://www.djcxy.com/p/73874.html

上一篇: 如何在删除{}括号时阻止VisualStudio扩展所有内容

下一篇: Backbone.View的样式属性