Created
December 18, 2014 13:32
-
-
Save redexp/cc52145e67ac77cea2c2 to your computer and use it in GitHub Desktop.
Example of backbone usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(function($) { | |
var Friend = Backbone.Model.extend({ | |
defaults: { | |
name: '' | |
} | |
}); | |
var FriendsList = Backbone.Collection.extend({ | |
model: Friend | |
}); | |
var friendTemplate = $('#friends > li').detach(); | |
var FriendView = Backbone.View.extend({ | |
initialize: function () { | |
var friendView = this, | |
friend = friendView.model; | |
friendView.setElement(friendTemplate.clone()); | |
friendView.$('[data-name]').val(friend.get('name')); | |
friendView.$el.on('click', '[data-delete]', function () { | |
friend.destroy(); | |
}); | |
friendView.listenTo(friend, 'destroy', friendView.remove); | |
} | |
}); | |
var FriendsListView = Backbone.View.extend({ | |
initialize: function (options) { | |
var listView = this, | |
friends = listView.collection; | |
listView.friendView = options.friendView; | |
listView.friendsViews = {}; | |
listView.listenTo(friends, 'add', listView.addFriend); | |
listView.listenTo(friends, 'remove', listView.removeFriend); | |
friends.forEach(listView.addFriend, listView); | |
}, | |
addFriend: function (friend) { | |
var friendView = new FriendView({ | |
model: friend | |
}); | |
this.friendsViews[friend.cid] = friendView; | |
this.$el.append(friendView.$el); | |
}, | |
removeFriend: function (friend) { | |
this.friendsViews[friend.cid].remove(); | |
this.friendsViews[friend.cid] = null; | |
} | |
}); | |
var friends = [1,2,3]; | |
friends = new FriendsList(friends.map(function (name) { | |
return { | |
name: name | |
}; | |
})); | |
var view = new FriendsListView({ | |
collection: friends, | |
el: '#friends' | |
}); | |
$('#add-friend').click(function () { | |
friends.add({name: ''}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment