I\'m starting out with Backbone.js so I must say I\'m not yet very familiar with the concepts.
I have predefined HTML and I want to use Backbone to manage this. This
Ok, I managed to figure it out.
The idea is to loop through your existing HTML using jQuery, then creating instances of views and models of it using the jquery selectors and the preloaded json.
HTML:
Harry
Jill
Bob
Javascript:
$(function() {
var PigModel = Backbone.Model.extend()
var PigView = Backbone.View.extend({
events: {
'change input': function(e) {
this.model.set('name', e.currentTarget.value)
this.render()
}
},
render: function() {
this.$el.html(
'' + this.model.get('name') + '
' +
''
)
}
})
var pig_data = [
{"name": "Harry"},
{"name": "Jill"},
{"name": "Bob"}
]
// the magic starts here
var pig_number = 0
$('.pig').each(function() {
new PigView({
el: this,
model: new PigModel(pig_data[pig_number])
})
})
})
Jsfiddle: http://jsfiddle.net/tU3Mt/1/
Like this I can serve a complete HTML page from the server, then load the desired elements into my backbone views/models and manage them from there.
About wether this is the way backbone should be used or not: It may not be the most logical/efficient way to do this from a developer point of view. However, I think this approach has some important benefits:
For some people these points may not be that important, because a webapp will be fast after it has been loaded and search engines won't have to crawl it. However in some situations you might have a mix of a website and a webapp, where the page needs to load fast, be crawlable but also have a responsive interface which is complex enough to make a developer want to use something like backbone. If somebody has other ideas about this I sure like to hear them.