Question

I'm trying to obtain the dimensions of a Backbone View with little to no luck. Is this because it's asynchronous and has yet to be added to the DOM?

var CardView = Backbone.View.extend({
    model: Card,
    tagName: 'div',
    className: 'card',
    events: function () {
        return (Modernizr.touch) ? {"touchstart": 'flip'} : {"mousedown": 'flip'};
    },
    initialize: function () {
        var faces = document.createElement('div');
        var front = document.createElement('div');
        var back = document.createElement('div');
        this.$faces = $('<div></div>')
            .addClass('faces')
            .append($('<figure></figure>').addClass('front'))
            .append($('<figure></figure>').addClass('back'))
        this.$el.append(this.$faces);
        this.model.on("change", this.render, this);
        // Trying to print the width of this view:
        console.log(this.$el.width());
        // => returns: 0;
    },
    flip: function () {
        this.model.flip();
    },
    render: function () {
        if (this.model.get("flipped")) {
            this.$faces.addClass("flipped");
        }
        else {
            this.$faces.removeClass("flipped");
        }
        this.$faces.find('.back').addClass(this.model.get('pattern'));
    }
});

If so then surely in a Collection view I should be able to access a rendered sub view like so:

var CardGridView = Backbone.View.extend({
    className: 'card-grid',
    defaults: {
        columns: 4
    },
    render: function () {
        this.collection.forEach(this.addCard, this);
    },
    addCard: function (card) {
        var cardView = new CardView({model: card});
        cardView.render();
        $(cardView.el).css({'left':this.collection.indexOf(card)*110+'px'});
        this.$el.append(cardView.el);
        // Trying to print the width of this view:
        console.log($(cardView.el).width());
        // => returns: 0;
    }
});
Was it helpful?

Solution

Unless you set it explicitly, the width and height is zero. When you insert the element into the document, the dimensions will be calculated

var div = document.createElement('div');
var text = document.createTextNode('Hello, world!');
div.appendChild(text);
/*
div.style.width = '100px';
div.style.height = '100px';
*/
console.log('before width=' + div.style.width + ';' + div.clientWidth);
document.body.appendChild(div);
console.log('after width=' + div.style.width + ';' + div.clientWidth);

See JSFiddle for playing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top