Search code examples
jquerybackbone.jsmustacheunderscore.js

Backbone.js - instantiate Models/Views from exisiting html


I've started looking at backbone.js today as a way to better organize the code in my application.

I was wondering (conceptually - so reply with pseudocode by all means) how I would use my existing html to create Backbone Models (and Views).

All of the tutorials I've found consist of using a blank html template and then injecting in the content using ajax. I don't want to do this.

If I have a collection of books.

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>My Book Collection</title>
</head>
<body>
    <head>

    </head>
    <body>
        <ul id="bookCollection">
            <li class="book" data-book-id="1"><input type="text" name="book_1_name" value="My Book A"/></li>
            <li class="book" data-book-id="2"><input type="text" name="book_2_name" value="My Book B"/></li>
            <li class="book" data-book-id="3"><input type="text" name="book_3_name" value="My Book C"/></li>
            <li class="book" data-book-id="4"><input type="text" name="book_4_name" value="My Book D"/></li>
            <li class="book" data-book-id="5"><input type="text" name="book_5_name" value="My Book E"/></li>
        </ul>
    </body>
</body>
</html>

At this stage I would like to start managing each book as a model, calling a function whenever book names are changed (just an alert in the function for proof of concept), and then calling a URL to sync changes to the model with my database.

Can anyone point me in the right direction for a way to do the above using existing html on a page?

If it makes a difference I plan on using mustache for my templating.


Solution

  • Backbone's views are always bound to a specfic html element (the view's attribute el). You could have something like a BookCollectionView bound to ul#bookCollection and a BookView bound to li.book, which should be fine with your current template structure.

    You can map a Book model to a view using a url to the model. If the model is fetched from that url and you have defined an event binding for the model change, the according view should refresh with the new model data. Same applies for the collection's url and a collection of books.

    There are not many good tutorials on backbone out i guess, but study something like http://liquidmedia.ca/blog/2011/02/backbone-js-part-3/ or http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/. Guess it is easier if you can come up with some more concrete questions!