Reputation: 1003
Ok, I have a simple JQuery plugin that when applied to a div will neatly load all the images within that div using a preloader image. This works fine.
However, in Backbone i'm appending data from JSON to a element after the page has been loaded. Therefore the code below won't work.
$(document).ready( ->
$("#theList").preloader()
)
So I need to put the "$("#theList").preloader()" in my render function, after my list is generated..
class HomeView extends Backbone.View
constructor: ->
super
initialize: ->
@isLoading = false
events: {
"click #nextPage": "nextPage"
"click #prevPage": "prevPage"
}
template: _.template($('#home').html())
theListTemplate: _.template($('#theList').html())
render: ->
$(@el).append(@template)
@loadResults()
$("#theList").preloader() #<----------------- DOESN'T WORK NOW
loadResults: () ->
@isLoading = true
Properties.fetch({
success: (data) =>
#Append properties to list
$('#theList').append(@theListTemplate({data: data.models, _:_})).listview('refresh')
error: ->
@isLoading = false
alert('Unable to load information')
})
However, now the line of code is within a Backbone View/Model/Controller or whatever, it doesn't work..
For reference I load my application like so..
$(document).ready( ->
console.log('document ready')
app.AppRouter = new AppRouter()
Backbone.history.start()
)
Any help would be much appreciated! Thanks.
Upvotes: 0
Views: 157
Reputation: 10627
Assuming the preloader isn't intended to operate on the nodes added in the loadResults#fetch#success
(since the fetch has not returned by the time you invoke the preloader), I suspect the issue is that, during the execution of the render()
function, the view's el
is not part of the DOM yet.
If you invoke HomeView
like
myHomeView = new HomeView()
$('some selector').append(myHomeView.render().el)
the HomeView's el has not yet been added to the DOM, its in a detached document.
Therefore the jQuery selector $("#theList")
returns an empty result - since its searching the DOM. This is easily verified by either console.log'n the result of that selector, or putting a breakpoint in using a debugger, and testing using the console.
Thankfully, the fix is easy. You need to reference the detached document by scoping the selector to the view, either using the jQuery reference scoped to the view:
@$("#theList").preloader()
or, by doing it yourself
$(@el).find("#theList").preloader()
Upvotes: 2