Lukmo
Lukmo

Reputation: 1688

Caching a view's sub-elements in backbone

I'm trying to cache (with a jQuery selector) some sub-elements in a view.

var theView = Backbone.View.extend({
    initialize:function(){
        this.$subEl = this.$el.find('.sub-el-class');
    },
    template: Handlebars.compile($('#view-template').html()),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        this.$subEl.hide();
        return this;
    }
});

When I render the view, $subEl (.sub-el-class) isn't hidden. I'd rather not have to use a jQuery selector each time I have to do something on the .sub-el-class element.

Any ideas what doesn't work with my code ?

Upvotes: 1

Views: 1105

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59773

Each time render is called, your code is recreating the entire contents of the view. $el represents the root node of the view. So your cached reference is lost (if there was one at all). You would need to change your code to grab the cached reference after the render is called. initialize doesn't call render, and it's executed just after the connection to the root element of your view.

var theView = Backbone.View.extend({
    initialize:function(){

    },
    template: Handlebars.compile($('#view-template').html()),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        this.$subEl = this.$el.find('.sub-el-class');
        this.$subEl.hide();
        return this;
    }
});

I'd also suggest that you add code to destroy any reference to the cached element when your view closes.

Upvotes: 2

Oden
Oden

Reputation: 754

this.$subEl = this.$el.find('.sub-el-class');

this is a pointer to .sub-el-class and you set it when you initialize your view.

every time you call this.$subEl is allready a jQuery object so it doesnt search the DOM again.

Upvotes: 3

Related Questions