2

I'm trying to learn the jade template system and backbone.js in the context of a (relatively simple) node.js webapp. I'm using express.js as my framework. Anyway, backbone.js looks really interesting and powerful, but I don't want to render my clients on the client side.

I'd rather render server-side with node and jade, send the client the rendered page, and just modify live content using backbone. What's the best way to go about this? In other words, what's the best way to use backbone with a page that's already rendered and structured? I realize that I'm not leveraging backbone to it's full power, but I'm pretty much just trying to use backbone rather than a bunch of jQuery selectors and event handlers.

mschallert
  • 4,129
  • 2
  • 17
  • 10
  • 2
    May I ask why you are so adamant about keeping view rendering logic on the server? Either way, you can reference an existing DOM element with a backbone view when instantiating, by passing the reference as the 'el' option to the view's constructor. ex: `new MyView({el: $('#myRenderedView')})`. – rr. May 10 '12 at 01:48
  • @rr.: A little more work and that's an answer. – mu is too short May 10 '12 at 02:11

1 Answers1

7

Your backbone view can reference an existing DOM element by passing a reference to the element as el when instantiating the view.

var myViewInstance = new MyViewClass({el: $('#existingDOMElement')});

Any event handlers you have declared in your view class will be bound to any child elements matching the event selectors. Ex:

<html>
    <body>
        <div id='myView'>
            <a class='foo'>Foo</a>
        </div>

        <script>
            var MyViewClass = Backbone.View.extend({
                events: {
                    'click .foo': 'fooClicked'
                },
                fooClicked: function(e) {
                    e.preventDefault();
                    console.log('.foo clicked');
                }
            });

            new MyViewClass({el: $('#myView')});
        </script>

    </body>
</html>
rr.
  • 6,484
  • 9
  • 40
  • 48