PageRenderTime 38ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/_posts/2012-03-26-backbone-notes-2.md

https://github.com/410675629/d48.github.com
Markdown | 61 lines | 45 code | 16 blank | 0 comment | 0 complexity | fee82e70453b637d92eb44784c304ee2 MD5 | raw file
  1. ---
  2. layout: post
  3. title: "Backbone.js notes Part 1"
  4. tags: [backbone.js, javascript]
  5. ---
  6. {% include JB/setup %}
  7. ## Notes on Backbone.js
  8. Dependency is [Underscore.js](http://documentcloud.github.com/underscore/)
  9. Underscore = library for Javascript functions that help in binding, templating, testing and more.
  10. Has 4 major classes:
  11. 1. Model
  12. 2. Collection
  13. 3. View
  14. 4. Router (was Controller)
  15. ### Model
  16. Represents a single entity, eg., a record in a database. Gives a way to read and write arbitrary properties or attributes on a data set.
  17. {% highlight js %}
  18. var ObjectName = Backbone.Model.extend({
  19. initialize: function(){
  20. console.log("init fired upon new");
  21. },
  22. defaults: {
  23. name: 'Default title',
  24. anotherProperty: 'random value'
  25. }
  26. });
  27. {% endhighlight %}
  28. ### Collection
  29. Essentially just a collection of models. Using database analogy, collections are the result from a query where the results are a number of records models.
  30. {% highlight js %}
  31. var ObjectCollection = Backbone.Collection.extend({
  32. model: ObjectName, //specify model that has been created
  33. someMethod: function() {
  34. return function(object) {
  35. object.get('specificPropertyName');
  36. };
  37. }
  38. });
  39. {% endhighlight %}
  40. ### View
  41. Views resemble controllers:
  42. 1. Listen to events thrown by the DOM and models/collections
  43. 2. Represent the application's state and model to the user.
  44. Sample templating libraries to use with `render` function: [Mustache.js](http://github.com/janl/mustache.js), [Haml-js](http://github.com/creationix/haml-js), [Eco](http://github.com/sstephenson/eco), as well as Underscore.js `.template`.
  45. Recommendation: whatever is used, nice if _never_ have to put strings of HTML in your Javascript.