Created
February 3, 2014 11:50
-
-
Save n1k0/8782600 to your computer and use it in GitHub Desktop.
Convenient way for a Backbone model view to listen to its model changes while being hold within a Collection
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<ul id="list"> | |
<li>nope</li> | |
</ul> | |
<input type="button" id="btn" value="change"> | |
<script src="vendor/jquery-1.9.1.js"></script> | |
<script src="vendor/underscore-1.4.4.js"></script> | |
<script src="vendor/backbone-1.0.0.js"></script> | |
<script> | |
jQuery(function($) { | |
"use strict"; | |
var Model = Backbone.Model.extend({ | |
defaults: {text: "foo"} | |
}); | |
var Collection = Backbone.Collection.extend({ | |
model: Model | |
}); | |
var modelA = new Model({text: "plop"}); | |
var modelB = new Model({text: "plip"}); | |
var collection = new Collection([modelA, modelB]); | |
var ModelView = Backbone.View.extend({ | |
tagName: "li", | |
initialize: function() { | |
this.listenTo(this.model, "change:text", this.render); | |
}, | |
render: function() { | |
this.$el.text(this.model.get("text")); | |
return this; | |
} | |
}); | |
var CollectionView = Backbone.View.extend({ | |
el: "ul#list", | |
views: [], | |
initialize: function() { | |
this.views = this.collection.map(function(model) { | |
return new ModelView({model: model}); | |
}); | |
}, | |
render: function() { | |
this.$el.html(this.views.map(function(view) { | |
return view.render().$el; | |
})); | |
} | |
}); | |
var collView = new CollectionView({collection: collection}); | |
collView.render(); | |
$("#btn").on("click", function(event) { | |
event.preventDefault(); | |
var found = collection.findWhere({text: "plop"}); | |
if (found) | |
found.set("text", "roudoudou"); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment