Coder Social home page Coder Social logo

addyosmani / backbone-fundamentals Goto Github PK

View Code? Open in Web Editor NEW
9.3K 341.0 1.4K 109.44 MB

:book: A creative-commons book on Backbone.js for beginners and advanced users alike

Home Page: http://addyosmani.github.io/backbone-fundamentals/

Makefile 0.05% HTML 36.58% CSS 9.16% JavaScript 54.16% Shell 0.01% Ruby 0.04%

backbone-fundamentals's Introduction

Developing Backbone.js Applications

About

This is the home of Developing Backbone.js Applications, an open-source book about the Backbone.js library for structuring JavaScript applications. It is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License and is currently available for early purchase via O'Reilly if you would like to support the project.

Contributing

We appreciate any and all efforts to help improve the book. Please note that the repository is structured as follows:

  • chapters - contains the source Markdown for each chapter. This is compiled into the HTML, ePub, Mobi and other formats found in the root of the project.
  • build - contains templates and metadata for compiling the book
  • img - contains image assets for the project
  • practicals - contains the source code for practicals

If you would like to submit pull requests, please feel free to apply them against the relevant markdown file in chapter. These can be previewed by running the build script via make, which will also generate updated versions of the other formats we support. Please ensure that you are only submitting the modified chapter file for your changes and not the compiled HTML/other format binaries.

Reviews

If you are interested in leaving a review to share your opinion on the book with others (it's always appreciated!), you can do so through O'Reilly.

Building

You can build the book using make or make -f Makefile. This will output the HTML, ePub, Mobi, PDF and RTF versions of the book.

Note: At this time, generating all of the above formats should be straight-forward with the exception of the PDF. We have an open pull-request for xelatex which is being considered and better guides for working around cross-platform PDF issues will be supplied as time allows.

Dependencies

  • Make
  • Pandoc
  • pdflatex (and recommended latex fonts)

Linux Debian based distros:

apt-get install pandoc texlive-latex-base texlive-fonts-recommended cm-super etoolbox

backbone-fundamentals's People

Contributors

1st avatar addyosmani avatar boushley avatar caillou avatar christopherscott avatar delba avatar eugeneglova avatar j-hannes avatar jackfranklin avatar jdreesen avatar jhonnycano avatar johanneslumpe avatar justindrake avatar kimjoar avatar markdalgleish avatar mdb avatar nicolechung avatar opengrid avatar rwstauner avatar sindresorhus avatar songtanmay avatar ssarj avatar tedjaniszewski avatar terryroe avatar theyak avatar tkrotoff avatar ugisozols avatar vitorbal avatar wibblymat avatar xmartin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone-fundamentals's Issues

minor typos and issues

for example Model.caption = 'A new caption' => for example, Model.caption = 'A new caption'
If you want to create a new element for you view => your view
this collections titles => collection's
broken link: Rebecca Murphey's excellent article on the topic.
get '/member/' do => should this be get '/members/' do??
so we can load and instantiation => instantiate
You'll commonly see both this and the configuration object included the => included in the
Whilst we get with Backbone out of the box can be terribly useful => fix this sentence
Remember, If there => if there
Applications'. -> Applications.'

possible bug is tutorial

@addyosmani it seems a bug for me but in this example

Photo = Backbone.Model.extend({
validate: function(attribs){
if(attribs.src == "placeholder.jpg"){
return "Remember to set a source for your image!";
}
},
...
var myPhoto = new Photo();
myPhoto.set({ title: "On the beach" });

validation is passes as ok since attribs.src is undefined - not == "placeholder.jpg"

The "MVC, MVP and Backbone.js" is super confusing

It reads like you're "thinking out loud" and trying to fit a square peg in to a round hole. I was less confused before I started reading this section :) In fact, I'd be inclined to just scrap the entire topic of MVC and MVP since it's clearly ambiguous with regards to Backbone. Backbone is not the only framework to suffer from this identity-crisis, either. I think there would be more value for newbies and seasoned veterans alike by just focusing simply on what types of problems Backbone is particularly suited to tackle. It would be way more concise, and a lot more compelling, IMHO.

minor: typo in .sql

the php version/mysql - the line making a column named after a reserved work needs to have ticks around it (order int) or else it constantly throws errors on any mysql version.

Clarifications on Collections

I found the Collection section a bit confusing.

This code

PhotoCollection = Backbone.Collection.extend({ model: Photo });

Feels to me like you are defining a type of collection. To actually use a photo collection I'd assume you have to new one up first. The capital letter in the variable name also seems to imply type to me. But you immediately started using PhotoCollection in the next code sample (by calling get on it, for example). So I guess extending Backbone.Collection gives you a collection object to work with immediately?

If that is the case, then later when you say var photoCollection = new Backbone.Collection([a,b]);, I guess you are newing up a base, generic collection. Why would you not say var photoCollection = new PhotoCollection([a, b]);?

model example (2 minor thing)

I created following example using the backbone-fundamentals readme file

Models example

While running the code found one minor issue (most probably my mistake :) )
There is some syntax error at L16 changeSrc

Also, initially got confused how to access the direct attributes.
I thought the way to access is direct attribute is myPhoto.src L44 direct access

can't read

"this tree is taking too long to generate"

Minor typo - double "of of"

In the section about Jasmine, there is a small typo with "of of" instead of just "of". You can find the typo simply by searching for the string "of of" through the document.

Mention objects in `validate` function are passed by shallow copy.

I just wanted to start off by saying, THANK YOU for writing this book and making it available to the public.

I think (and this is just my personal opinion) that it is important to note that Backbone passed the attributes object by shallow copy to the validate function using Underscore's _.extend function. This means that you can't change any Number or String or Boolean attribute by reference in the way that you would expect a JavaScript object to behave normally. However, because shallow copy does not copy objects by copying them, but by reference, you can change the attributes on those objects)

Example : http://jsfiddle.net/2NdDY/7/

Maybe I am the only one who thinks that attributes should be allowed to change when setting?

Is this more of an edge case? (e.g. filtering words or trimming strings)

Wishlist

Items I or others would like covered:

  • Full tutorials for the practical section of the book. Code for both are currently available, but the dialog needs to be written around them
  • More about RESTful applications with Backbone. Lots of posts on this but not enough covering modern stacks (Node/Express/MongoDB etc)
  • Backbone Layout manager. How does this fit in? Where can it be useful?

Feel free to add more to this list in the comments :)

Extra info on binding view-model and template in 'Basics'

Hi,

In Basics -> Views -> Understanding render():

  • Where it says '... I'm passing the markup from a template with id results-template to _.template() to be compiled..': Would it be possible to actually show results-template somewhere? It might be rather vague for newbies (such as me) as it is hard to know what that actually looks like
  • Where it says '...Next, I set the html of the el DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.': might it be beneficial to actually show code of associating a model with that view?

Both remarks are in the context that you're following along with the code in the book, trying to let the small examples work in your own IDE (as I'm trying to do). I get sort of stuck here since there doesn't seem anything that can actually 'do anything'.

Just my 2 cents to provide some feedback perspective from an actual Backbone.js beginner ;-)

Cheers,

Dieter

order of loading Underscore and Backbone - dependency issue.

The modular mobile app has an issue with loading underscore and backbone.

In backbone-fundamentals -> practicals -> modular-mobile-app -> app -> main.js

The Underscore module needs to be loaded before Backbone.js for the code to work

earlier code

Line : 16 ['require', 'backbone', 'jquery', 'underscore' ],
Line : 17 function( require, Backbone, $, _ ) {

should be

Line 16 ['require','underscore', 'backbone', 'jquery' ],
Line : 17 function( require, _, Backbone, $) {

typo in git clone path

git clone git://github.com/addyosmani/addyosmani/backbone-boilerplates.git

should be:

git clone git://github.com/addyosmani//backbone-boilerplates.git

Could not find .png files

When i ran the pandoc command it failed with "./http://addyosmani.com/gyazo/3e5545.png: openBinaryFile: does not exist (No such file or directory)".
It looked as if it was trying to find the file in the local directory rather via the web as all three png files existed at those location. So downloaded them to the root directory i was running pandoc and the xml file in and it works fine.

However is there a way in MD that the remote file can be specified? Currently it looks like this

screenshot 2

Backbone(underscore) issue with Require.js

Since I'm using node.js on the server side I prefer the "simplified CommonJS wrapping" to define modules like this:

define(function(require) {
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');

// require jquery plugins
require('jqueryui');
require('jquery-plugins/jquery.gritter');
require('jquery-plugins/same-height');

return Backbone.View.extend({ ... });

});

However, Backbone.View.extend() always raised the error "Backbone is null".

Google lead me to this thread:

jashkenas/underscore@0d4b124

and wrapping Backbone into an AMD module like this:

define(['jquery', 'underscore'], function($, _){
// paste Backbone.js source code here
return Backbone;
});

fixed the issue.

I think this is worth noting it in your book.

Stephan

reviews?

re:http://shop.oreilly.com/product/0636920025344.do

Hey, are you reading the reviews?

Please do, i'm new to backbone too - it kept me from purchasing your book... include diagrams, flow, (topically) explain theories as you build, at a suitable point, if led to, offer more depth to the theory.

OR better yet, just use some very cut and dry examples to show the features of the framework, then write another book explaining advanced usage?

j.m.h.o :)

Small confusion of toJSON and JSON.stringify

In The Basics -> Model -> Getters&Setters -> Model.get() it is said that Model.toJSON() returns the JSON string as shown in the code example.
However, toJSON() rather returns an object. I think you might be referring to JSON.stringify()

As shown here: http://documentcloud.github.com/backbone/#Model-toJSON

(note: I'm just following along in the book since it's my first real Backbone.js confrontation, so I might be missing something :-) )

Cheers,

Dieter

More minor stuff

  1. "one important area that that" -> word repeated

  2. "AMD module format" is somewhat redundant

  3. "Backbone?." extra dot

Thanks for this tutorial!

Section: working with nested models

It would be great to cover this in a book. Yes, I know that there are plenty of plugins that handle such situations, but anyway this is quite confusing topic. For example, what will be the best approach to render multilevel menu from nested data, like categories and subcategories of goods.

Revise content for Backbone 0.9.2

A number of additions and revisions have been made to Backbone in the most recent 0.9.x releases which should be reflected in the book. I would ideally like to get this in prior to any major new sections being written up.

From the docs:

  • If you've ever manually set this.el in a Backbone View to be a particular DOM element, you'll want to use setElement instead.
  • Creating and destroying models is now optimistic. Pass {wait: true} if you need the previous behavior of waiting for the server to acknowledge success. You can now also pass {wait: true} to save calls.
  • If you have been writing a fair amount of $(view.el), there's now a cached reference for that jQuery object: $el.
  • If you're upgrading, make sure you also upgrade your version of Underscore.js to the latest โ€” 1.3.1 or greater.
    model.set will no longer trigger change events when setting a value with {silent: true} then setting it back to its original value. Similarly, after changing an attribute silently, that change:attribute event will fire during the next change.
  • Since view.$(selector) is now equivalent to view.$el.find(selector) rather than $(selector, view.el) it can no longer be used when selector is an HTML string or DOM element.

Typo in PhotosController

From the blog:

spelling mistake:

=== editd

In this example, we're going to have a controller called `PhotosController which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user editd the photo meta-data) the corresonding model does too.

Where do you bind a model and a view?

I'm reading the 'Views' section.

It's clear how you create a view, but not how you bind it to a model.

In the example code for "Creating new views", there's a call in the render function which use this.model.toJSON() as a parameter.

It would be useful to have something in this example code to show how this gets set.

Some minor tweaks to spacing

  1. Consider expanding "qSA" for the new-comer.

  2. "It's considered optional" -> it is optional?

  3. "title = myPhoto.get("title")" -> too many spaces

  4. "Accessing Model.attributes directly is fine for reading or cloning data, but ideally shouldn't be used to for attribute manipulation." -> Jeremy recommends not touching at Model.attributes at all. For reading or cloning data, he suggests toJSON.

  5. "in scenario where" -> a word is missing

  6. There are minor spacing consistency problems in the fragments of code throughout. For example "_.template( $("#results-template").html());"

  7. In the "What is 'el'?" section you don't emphasize that you can use a combination of the methods to define el

  8. "render() is a function that should always be overridden" -> render() is optional

That's all for now. Let me know if this is useful.

Replace examples in 'Basics' section

In order to make the 'Basics' section more consistent with the rest of the book, I think it would make sense to move away from the photo gallery example described across models, views, collections and routers and instead use https://github.com/addyosmani/backbone-koans/blob/master/js/todos.js as the basis for the examples instead.

This solves a number of problems including allowing readers to actually build and run something by the end of this section of the book. At the moment, the code used was not written in a way in which the code examples could be combined to create something runnable. I will hopefully get a chance to work on this soon.

AppView.addOne() doesn't see the view members when fetch() is called

More of a question than issue:

in modular-todo-app -> app.js, add this code:

addOne: function(todo) {
console.log("addOne: " + this.statsTemplate);
....

While this works for items added after app is loaded, for items fetched from localStorage it will give
addOne: undefined

Any explanation why and how to fix it? (i'm trying to access any AppView member, "statsTemplate" is just an example)
Thanks

Pandoc epub generation

Receiving error when generating pandoc with the following:
$ pandoc -f markdown -t epub --epub-metadata=metadata.xml -o backbone-fundamentals.epub README.md

pandoc: ./http://addyosmani.com/gyazo/3e5545.png: openBinaryFile: does not exist (No such file or directory)

Appears to refer to line 3734 README.md. Am able to browse to image link.

No bookmarks

This looks like a very useful resource, but putting it all in a single README.md has one major drawback:

You can't link to a specific chapter of the book (and I don't think it's possible to add id attributes using Markdown).

Convert project to using grunt.

With the latest set of updates, although a static HTML file is being provided for an online version of the book, these is still a need to include additional content (social sharing buttons etc) as a part of index.md for conversion as we have no other build process.

I want to avoid this completely. We should have a simple set of template strings in index.md which can then be replaced with any additional blocks needed for the online version of the book. This will make it easier for anyone wishing to use say, Pandoc to create formats of the book.

https://github.com/cowboy/grunt/blob/master/docs/task_concat.md will help with this.

Which content of backbone fundamentals?

Hi,
as I've already mentioned in another issue, I would prefer to have design patterns
in a seperate book ( as you do) as well as server side technologies.

I'm going to commit to this book,but for me it's not clear, what the content of the book should be.
I'd like to see more practical examples and fundamentals like described here:
http://aaronhardy.com/javascript/javascript-architecture-backbone-js-routers/

How do you think about it, Addy?
Probably it's a good idea to think, discuss and vote about a clear and nice structure of the content.

Consistency with using `new`

Sometimes you write:

Photo = new Backbone.Model.extend({

Some other times you write:

Photo = Backbone.Model.extend({

epub chokes aldiko

Aldiko reader chokes and gives error of being "unable to load data " when trying to open this epub

Unnecessary test

It might be that I've misunderstood something from the text, but is the first text example under http://addyosmani.github.com/backbone-fundamentals/#collections-2 an example of a good test? I've copied it here for reference:

describe('Tests for TodoList', function() {

    it('Can add Model instances as objects and arrays.', function() {
        var todos = new TodoList();

        expect(todos.length).toBe(0);

        todos.add({ text: 'Clean the kitchen' });

        // how many todos have been added so far?
        expect(todos.length).toBe(1);

        todos.add([
            { text: 'Do the laundry', done: true }, 
            { text: 'Go to the gym'}
        ]);

        // how many are there in total now?
        expect(todos.length).toBe(3);
    });
...

This test only ensures that the Backbone framework works as expected, doesn't it?

Invalid reference to platform.twitter.com/widgets.js

Google Chrome chokes at load of index.html because the twitter widget script has a undefined protocol.

In file: index.html
Line 40:

...  src="//platform.twitter.com/widgets.js" ... "//platform.twitter.com/widgets.js" ....

Fix
Use http:// instead of //

...  src="http://platform.twitter.com/widgets.js" ... "http://platform.twitter.com/widgets.js" ....

Minor typo

There is a minor typo in the section 'The Basics - Views - Creating new views'. 'this.el.html' is used instead of '$(this.el).html'.

Duplicate wording in "Nested namespacing"

Just below the Yahoo code snippet:

This is readable, clearly organized, and is a relatively safe way of namespacing your Backbone application. It may be familiar if you've used other languages.

The only real caveat however is that it requires your browser's JavaScript engine first locating the galleryApp object and then digging down until it gets to the function you actually wish to use.

This approach does require your browser's JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you're calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the 'nested' approach to be quite negligible.

These two lines should ideally be merged into one sentence. :)

Syntactic sugar for require([]) calls

It would be great for require([], callback) calls to also allow the require syntactic sugar. I imagine that this would work by passing a callback as the only argument:

require(function(require) {
  var lib1 = require("src/my/lib1"),
      lib2 = require("src/my/lib2");

  // ...
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.