PageRenderTime 46ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/recipe-app/js/views/recipe-list.js

https://github.com/ifandelse/devlink2012-Introduction-to-Backbone.js
JavaScript | 46 lines | 29 code | 4 blank | 13 comment | 0 complexity | f869b8042dc2f0444b67f5dc03fed521 MD5 | raw file
Possible License(s): MIT
  1. /*
  2. Fairly straightforward view that manages the display of recipes in the Collection
  3. that acts as the model to this view. You'll notice that even though this view has
  4. no other model instances (only the collection), I still pass it into the template
  5. rendering function as the member of an object. This is because in most circumstances
  6. that I've seen - as an app grows, it becomes necessary for collection views to have
  7. model data in addition to the collection itself, and having the template expect an
  8. object allows an easy point in which to simply add the new data that should be displayed.
  9. Note that calling 'fetch' automatically on init - while convenient - can be dangerous.
  10. */
  11. define( [
  12. 'backbone',
  13. 'underscore',
  14. 'jquery',
  15. 'models/recipe-list-model',
  16. 'text!views/templates/recipe-list.html'
  17. ], function ( Backbone, _, $, RecipeListCollection, template ) {
  18. return Backbone.View.extend( {
  19. el: "#content",
  20. // selectors will be found within the DOM tree under this view's top level element
  21. events: {
  22. "click .remove-recipe" : "removeRecipe"
  23. },
  24. initialize: function(options) {
  25. _.bindAll(this); // sets the "this" context for all the methods on this view object to the view itself
  26. this.template = _.template(template);
  27. // this is more for convenience - the collection is accessible on the app object
  28. // but I'm getting a local handle to it for brevity's sake
  29. recipeApp.models.recipeList = this.collection = new RecipeListCollection();
  30. this.collection.on("add reset remove", this.render);
  31. this.collection.fetch(); // not always the wisest of choices in "initialize"
  32. },
  33. render: function() {
  34. this.$el.html(this.template({ recipes: this.collection.toJSON() }));
  35. },
  36. removeRecipe: function (e) {
  37. e.preventDefault();
  38. var elem = $( e.currentTarget );
  39. this.collection.remove(this.collection.get(elem.attr("data-val")));
  40. }
  41. } );
  42. } );