attaching backbone.js views to existing elements vs. inserting el into the DOM

Solution 1:

There's absolutely nothing wrong with the idea of attaching a view to an existing DOM node.

You can even just put the el as a property on your view.

window.MyView = Backbone.View.extend( {
     el: '#myView',
     initialize: function () {
          this.template = _.template($('#myViewContents').html());
          this.render(); 
     },
     render: function () {
          this.$el.html(this.template()); // this.$el is a jQuery wrapped el var
          return this;
     }
});
$(function () {
    window.myView = new MyView();
});

What I recommend is, do what works... The beauty of Backbone is that it is flexible and will meet your needs.

As far as common patterns are concerned, generally I find myself having a main view to keep track of over views, then maybe a list view and individual item views.

Another common pattern as far as initialization is concerned is to have some sort of App object to manage stuff...

var App = (function ($, Backbone, global) {
    var init = function () {
        global.myView = new myView();
    };

    return {
        init: init
    };
}(jQuery, Backbone, window));

$(function () {
    App.init();
});

Like I said before though, there's really no WRONG way of doing things, just do what works. :)

Feel free to hit me up on twitter @jcreamer898 if you need any more help, also check out @derickbailey, he's kind of a BB guru.

Have fun!

Solution 2:

You can also send an HTML DOM Element object into the view as the 'el' property of the options.

window.MyView = Backbone.View.extend( {
     initialize: function () {
          this.template = _.template($('#myViewContents').html());
          this.render(); 
     },
     render: function () {
          this.$el.html(this.template()); // this.$el is a jQuery wrapped el var
          return this;
     }
});
$(function () {
    window.myView = new MyView({
        el: document.getElementById('myView')
    });
});