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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With