PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/recipe-app/js/models/recipe-model.js

https://github.com/ifandelse/devlink2012-Introduction-to-Backbone.js
JavaScript | 64 lines | 40 code | 5 blank | 19 comment | 6 complexity | 2d7015215aff3070d7f3d285f209e7e0 MD5 | raw file
Possible License(s): MIT
  1. /*
  2. Recipe model. This provides the model instance for both existing recipes
  3. that live in the recipe-list-collection, but also stand alone instance for
  4. creating a new recipe. If this model is being used to create a *new* recipe,
  5. the result (once validation passes) is "toJSON()-ed" and passed into the "add"
  6. method on the collection, and then this instance is cleared.
  7. */
  8. define( [
  9. 'backbone',
  10. 'jquery'
  11. ], function ( Backbone, $ ) {
  12. return Backbone.Model.extend( {
  13. //urlRoot: "/api/recipe",
  14. defaults: {
  15. id: null, // For Backbone to consider this a new model, use undefined or null
  16. title: "",
  17. description: "",
  18. items: [],
  19. steps: []
  20. },
  21. // simple function to capture the state of a model
  22. getMemento: function() {
  23. this.memento = this.toJSON();
  24. },
  25. // if we've stored a memento, this can reset the model back to that state
  26. applyMemento: function() {
  27. if(this.memento) {
  28. this.set(this.memento);
  29. }
  30. },
  31. /*
  32. One of the hidden gotchas of the built in validation logic
  33. (hidden in _validate, which in turn calls your implementation
  34. of validate) is that the entire model's attribute are passed
  35. in, and not just the value(s) you are setting. You can avoid
  36. an invalid model from keeping your values from being set by
  37. providing the { silent: true } option, but I personally find
  38. that frustrating!
  39. */
  40. validate: function(attrs) {
  41. var errors = [];
  42. if(!attrs.title) {
  43. errors.push("You must include a title.")
  44. }
  45. if(!attrs.description) {
  46. errors.push("You must include a description.")
  47. }
  48. if(!attrs.items.length) {
  49. errors.push("You must include at least one required item.")
  50. }
  51. if(!attrs.steps.length) {
  52. errors.push("You must include at least one step.")
  53. }
  54. if(errors.length) {
  55. return { errors: errors };
  56. }
  57. }
  58. } );
  59. } );