0

I have Backbone view. It load content (component on backbone with AJAX):

        render: function () {
            var self = this;
            $.get('/Blog', request, function (data) {
                self.$el.html(data);
                model.trigger('blogContainerLoaded');
            });
        }

Component code:

 window.App = {


init: function (options) {
    var BlogModel = Backbone.Model.extend({
    });

    var model = new BlogModel();

    var BlogController = Backbone.Router.extend({
        routes: {
            "": "posts",
            "posts": "posts",
            "posts/:postId": "post",
            "posts/:postId/": "post",
        },
        posts: function (anchor) {
            window.App.views.posts.render(anchor);
        },
        post: function (postId, commentId) {
            window.App.views.post.render(postId, commentId);
        },
    });

    var controller = new BlogController();
    if (notLoaded) {
        var views = {
            posts: new PostListView({ model: model, controller: controller }),
            post: new PostView({ model: model, controller: controller }),
        };
        this.views = views;
        Backbone.history.start();
    }
}

};

var PostListView = Backbone.View.extend({
el: $(".posts"),
events: {
    "click .js-edit-message": "editMessage",
    "click .js-open-post": "navigateToPost",
    "click .js-move-post": "move"
},
editMessage: function () {
    debugger;
},
navigateToPost: function () {
    debugger;
},
move: function () {
    debugger;
},

All html code loads with ajax. It works, but events (clicks and other) not firing! When I load Blog component without AJAX - events working. Please Help!

1 Answers1

1

Most likely your view is instantiated before your ajax call is complete. Because ajax is asynchronous, while it does load (eventually) your code to initialize the view runs first. Thus, when your view is looking to attach the events to your DOM, the necessary elements are not present.

This would also explain why when you eliminate the ajax portion of it, the code works (it's now synchronous and the DOM is present before you initialize your view code.)

Try putting your initialization code inside the ajax callback like this: (if possible)

    render: function () {
        var self = this;
        $.get('/Blog', request, function (data) {
            self.$el.html(data);

            self.blogContainer = new BlogContainerView();  // Or however you do it
        });
    }

Another possibility is to keep your trigger.('blogContentLoaded') then attach the events at that time. Backbone.View's delegateEvents() method might be useful in your case.

Or something of that nature. Now you're guaranteed that the DOM is available for your View object to attach events to.

jmk2142
  • 8,581
  • 3
  • 31
  • 47