Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element not ready after Backbone.Marionette.ItemView render?

I'm unable to access an element even in the onRender method of a Backbone.Marionette.ItemView.

For example, I have:

Template:

<input type="text" id="searchBox">`

ItemView:

View = Backbone.Marionette.ItemView.extend
    template: searchTemplate
    onRender:
        @setTypeahead ['a', 'b', 'c', 'd']
    setTypeahead: (valueArray) ->
        console.log $('#searchBox')
        $('#searchBox').typeahead
            source: valueArray

Unexpectedly, the object logged to the console does NOT contain the input element. The selector didn't work. Why is that?

The comments inside the tiny code block on Marionette's github here mentions "manipulate the el here. it's already been rendered, and is full of the view's HTML, ready to go." Unless I've misunderstood that, I would think the template would be rendered and ready to manipulate inside the onRender function of the ItemView.

like image 896
Depressio Avatar asked Jan 12 '13 00:01

Depressio


2 Answers

You need to scope your jQuery selector to the view, because the HTML elements are not yet added to the DOM.


View = Backbone.Marionette.ItemView.extend
    template: searchTemplate
    onRender:
        @setTypeahead ['a', 'b', 'c', 'd']
    setTypeahead: (valueArray) ->
        console.log $('#searchBox')

        @$('#searchBox').typeahead
            source: valueArray

The reason using onShow works, is because the elements are added to the DOM at that point. But this is a bad idea because it would allow the selector to find all elements with the specified query in the page, not just the one for this specific view instance. By using @$("#searchBox") you are scoping the jQuery selector to the view instance, and are able to find the element within the view's $el even if the view has not been added to the DOM yet.

like image 84
Derick Bailey Avatar answered Oct 31 '22 14:10

Derick Bailey


OK, of course as soon as I finally decide to ask here, I answer the question myself.

I should be using onShow instead of onRender. The Marionette documentation still seems to be misleading, IMO.

like image 44
Depressio Avatar answered Oct 31 '22 13:10

Depressio