Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created January 7, 2013 09:36
Show Gist options
  • Select an option

  • Save daGrevis/4473711 to your computer and use it in GitHub Desktop.

Select an option

Save daGrevis/4473711 to your computer and use it in GitHub Desktop.
"use strict"
;(function($) {
$(function() {
var bookmarks = [
{url: "http://google.com/", title: "Google", category: "Search engines"},
{url: "http://duckduckgo.com/", title: "DuckDuckGo", category: "Search engines"},
{url: "http://twitter.com/", title: "Twitter", category: "Social networks"},
{url: "http://facebook.com/", title: "Facebook", category: "Social networks"},
{url: "http://dagrevis.lv/", title: "daGrevis.lv", category: "Blogs"}
]
var Bookmark = Backbone.Model
var Directory = Backbone.Collection.extend({
model: Bookmark
})
var BookmarkView = Backbone.View.extend({
tagName: "div",
className: "single_bookmark",
template: $("#single_bookmark").html(),
render: function() {
var template = _.template(this.template)
this.$el.html(template(this.model.toJSON()))
return this
}
})
var DirectoryView = Backbone.View.extend({
el: $("#wrapper"),
events: {
"change #filter select": "set_filter"
},
initialize: function() {
this.collection = new Directory(bookmarks)
this.render()
this.$el.find("#filter").append(this.create_select())
},
render: function() {
var that = this
that.$el.find("#bookmarks").html("")
_.each(this.collection.models, function(item) {
that.render_bookmark(item)
})
},
render_bookmark: function(item) {
var bookmark_view = new BookmarkView({
model: item
})
this.$el.find("#bookmarks").append(bookmark_view.render().el)
},
get_categories: function() {
return _.uniq(this.collection.pluck("category"))
},
create_select: function() {
var select = $("<select>")
, categories = this.get_categories()
categories.unshift("Everything")
_.each(categories, function(item) {
$("<option>", {
value: item,
text: item
}).appendTo(select)
})
return select
},
set_filter: function(e) {
this.selected_category = $(e.currentTarget).val()
this.apply_filter()
},
apply_filter: function() {
if (this.selected_category === "Everything") {
this.collection.reset(bookmarks)
} else {
var selected_category = this.selected_category
, filtered = _.filter(bookmarks, function(item) {
return item.category === selected_category
})
this.collection.reset(filtered)
}
this.render()
}
})
new DirectoryView()
})
}(jQuery))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment