Andrii Furmanets
Andrii Furmanets

Reputation: 1161

backbonejs how to call function when page loaded

I have function with the simple selector $(.some-class) not with this.$(.some-class). I call this function in the render. But this function cannot find the .some-class. As I understand I must call function when DOM is loaded. How can I do that?

File with Backbone view:

var DocumentView = Backbone.View.extend({
  render: function(){
    someFunction('.some-class');
  },
});

File with the function:

function someFunction(target) {
  $(target);
}

I cannot find an element with class '.some-class', with backbone, but when page is loaded I can do that.

Upvotes: 0

Views: 1308

Answers (1)

skay-
skay-

Reputation: 1576

Since you are using Backbone you are already using jQuery. Having said that, you can put all your code within the jQuery callback as follows:

$(function() {
    function someFunction(target) {
      $(target);
    }
    ...
    ...
    var DocumentView = Backbone.View.extend({
       render: function(){
           someFunction('.some-class');
       },
   });
})

This ensure that the code will only get called once the DOM has fully loaded (dom ready jquery)

Another alternative, is to put all your code (or the javascript files) at just before the closing body element.

Upvotes: 1

Related Questions