1

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 ?

2 Answers 2

3
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.

3
  • Ok, that's a good thing. Isn't there any way to cache it though ? I'd rather use a variable such as $subEl instead of a find each time, for maintainability purposes.
    – Lukmo
    Feb 22, 2013 at 10:57
  • 1
    its allready cached after initialize on var this.$subEl, you dont need to do anything else.
    – Oden
    Feb 22, 2013 at 11:38
  • This shouldn't work. The problem is that when we initialize the view, most of the times the object still doesn't exist in the DOM, so we are caching something that doesn't exist. This reference is not dynamic: if we render this object afterwards, this.$subEl will still be empty.
    – user900362
    May 11, 2015 at 23:35
2

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.