Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Created November 15, 2010 08:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkuklis/700149 to your computer and use it in GitHub Desktop.
Save mkuklis/700149 to your computer and use it in GitHub Desktop.
playing with backbone
$(function() {
// data comes from server
var data = {title: "header title", body: "body title", background_color: "#ffffff"};
// setup site model and extend it with data from server
var Site = Backbone.Model.extend(data);
// header view
var HeaderView = Backbone.View.extend({
el: $("#header"),
template: $('#headerTemplate').html(),
initialize: function() {
_.bindAll(this, "render");
// bind to specific field on the model
this.model.bind('change:title', this.render);
},
render: function() {
$(this.el).html(Mustache.to_html(this.template, this.model.toJSON()));
return this;
}
});
// body view
var BodyView = Backbone.View.extend({
el: $("#body"),
template: $('#bodyTemplate').html(),
initialize: function() {
_.bindAll(this, "render", "setBackgroundColor");
// bind to specific field on the model
this.model.bind('change:body', this.render);
this.model.bind('change:background_color', this.setBackgroundColor);
},
render: function() {
$(this.el).html(Mustache.to_html(this.template, this.model.toJSON()));
return this;
},
setBackgroundColor: function(model, field) {
$(this.el).css('background-color', field);
}
});
// glue stuff together
var site = new Site();
// same model attached to different views
var header = new HeaderView({model: site});
var body = new BodyView({model: site});
// changes come from panel/widgets
site.set({title: "title changed!"});
site.set({body: "body changed!"});
site.set({background_color: "#aaa"});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment