I am a complete noob to backbone and decided to try and create a web page or two based using backbone as a structure. My first task is to create a basic navigation.
My page lives here http://dalydd.com/projects/backbone.html
here is my javascript thus fur to create that one little navigation item
(function($){
var NavigationItem = Backbone.Model.extend({
defaults: {
name: '',
href: '',
last: false,
id: ''
},
initialize: function() {
}
});
var home = new NavigationItem({name: 'home', href: '/home', id:'home'});
var about = new NavigationItem({name:'about', href: '/about'});
var contact = new NavigationItem({name:'contact', href: '/contact', last:true});
var TopNav = Backbone.Collection.extend({
model: NavigationItem,
});
var topNav = new TopNav();
NavView = Backbone.View.extend({
el : $('ul'),
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render : function() {
var self = this;
$(this.el).append("<li><a href="+home.get('href')+">"+home.get('name')+"</a></li>")
}
});
var navView = new NavView();
})(jQuery);
My question(s) is how can i loop through each instantiated nav item and append it to the ul element w/o writing each one out
My other question is can you use backbone without data-binding your scripts, data-binding seems like obtrusive javascript in a way. Also does one need to become an expert in underscore.js in order to use backbone properly. Underscore just seems like a bunch of predefined functions – doesn’t jQuery offer some of the same functions as utility functions? so why even use underscore is because of the data binding? can you use backbone w/o data-binding everything? I’m having a difficult time learning backbone because I feel like it mimics a classical language instead of using something like Object.create() like Douglas Crockford uses. Are there any resources out there that just build a basic page using backbone? I know it’s not intended for small applications but I’m still trying to figure out how it all works.
Again any help/resources is appreciated. I just started working for a large corporation and they are looking to implement an MVC framework for javascript and backbone seems the ideal choice but I am struggling thus far to learn.
Backbone provides Collections for this matter. Any Backbone View can hold a Model or a Collection. In your example you could build a collection like this:
Then, you would create the collection and append all of the items:
and then you can make a view which just displays it all:
being this view something like:
You could have a view for displaying each of the individual items (and a
subviewsattribute, so you can refer to them) or even a template which iterates over this collection.