Skip to content

Instantly share code, notes, and snippets.

@justjohn
Created February 21, 2012 15:38
Show Gist options
  • Save justjohn/1877069 to your computer and use it in GitHub Desktop.
Save justjohn/1877069 to your computer and use it in GitHub Desktop.
Backbone view for a tweet
module.declare(
[
{ backbone: 'vendor/backbone' }
, { twig: "vendor/twig" }
, { tweet: "js/model/tweet" }
]
, function (require, exports, module) {
var Backbone = require("backbone")
, twig = require("twig").twig
// Load the template for a "Tweet"
// This template only needs to be loaded once. It will be
// compiled at load time and can be rendered separately
// for each Tweet.
, template = twig({
href: 'templates/tweet.twig'
, async: false
})
, TweetView = Backbone.View.extend({
tagName: "li"
, className: "tweet"
, events: {
"click .star": "star"
}
// Create the Tweet view
, initialize: function() {
// Re-render the tweet if the model changes
this.model.bind('change', this.render, this);
// Remove the Tweet if the model is removed.
this.model.bind('destroy', this.remove, this);
}
// Render the tweet Twig template with the contents
// of the model
, render: function() {
// Pass in an object representing the Tweet to serve
// as the render context for the template and inject it
// into the View.
$(this.el).html( template.render(this.model.toJSON()) );
return this;
}
// Remove the tweet view from it's container (a FeedView)
, remove: function() {
$(this.el).remove();
}
// Star a tweet
, star: function() {
this.model.set({
star: !this.model.get("star")
});
this.model.save();
// We don't have to re-render the view here, the "change"
// event on the model will trigger the render.
}
});
exports.TweetView = TweetView;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment