├── .gitignore ├── README.rst ├── __init__.py ├── manage.py ├── polls.db ├── polls ├── __init__.py ├── admin.py ├── fixtures │ ├── polls_forms_testdata.json │ └── polls_views_testdata.json ├── forms.py ├── models.py ├── tests │ ├── __init__.py │ ├── forms.py │ ├── models.py │ └── views.py ├── urls.py └── views.py ├── polls_api ├── __init__.py ├── resources.py ├── urls.py └── views.py ├── requirements.txt ├── settings.py ├── static ├── libs │ ├── backbone.js │ ├── jquery.js │ └── underscore.js └── polls │ ├── models.js │ ├── routes.js │ ├── styles.css │ ├── utils.js │ └── views.js ├── templates ├── 404.html ├── 500.html └── polls │ ├── base.html │ ├── detail.html │ ├── index.html │ └── results.html └── urls.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pyc 3 | *~ 4 | env/ 5 | .env/ 6 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | Guide to Django+Backbone.js 3 | =========================== 4 | 5 | For this example, I'm going to use the classic Django polls tutorial project -- 6 | specifically starting from Daniel Lindsley's awesome guide to testing project. 7 | The source is available `on GitHub 8 | `_. This version is 9 | mostly identical to the one in the Django tutorial, except it has: 10 | 11 | * tests 12 | * form validation 13 | 14 | We will enhance this polls app to have a more interactive feel, appropriate for 15 | a live voting situation. 16 | 17 | Step 0: Getting Set Up 18 | ====================== 19 | 20 | The first thing I want to do is get the initial code. It's all available on 21 | `GitHub `_:: 22 | 23 | git clone git://github.com/mjumbewu/guide-to-testing-in-django.git 24 | 25 | Of course, I want to set up an environment and actually install Django:: 26 | 27 | cd guide-to-testing-in-django 28 | virtualenv env 29 | source env/bin/activate 30 | pip install django 31 | 32 | (We will try to keep the dependency list short for this project.) 33 | 34 | Initialize the project, and then check to make sure that everything is working 35 | as expected. There is a SQLite database bundled with the project (username: 36 | admin, password: abc123), so you should 37 | just be able to start running. First, make sure the tests pass:: 38 | 39 | ./manage.py test polls 40 | 41 | You should get output that looks like:: 42 | 43 | Creating test database for alias 'default'... 44 | ............ 45 | ---------------------------------------------------------------------- 46 | Ran 12 tests in 0.398s 47 | 48 | OK 49 | Destroying test database for alias 'default'... 50 | 51 | Now, run the server:: 52 | 53 | ./manage.py runserver 54 | 55 | In your browser, go to *http://localhost:8000/polls/* and click around for a 56 | while. If everything looks alright, let's continue. 57 | 58 | **Up until this point, the project code corresponds to the tag bb01-initial. 59 | The next few sections describe the bb02-explore_models tag.** 60 | 61 | Step 1: Setting Up the JavaScript Dependencies 62 | ============================================== 63 | 64 | We will have at least three JavaScript library dependencies: 65 | 66 | * `Backbone.js`_, which in turn depends on both 67 | * `Underscore.js`_, and (optionally) 68 | * `jQuery`_ 69 | 70 | *Underscore.js* fills in the gaps in JavaScript. It is "a utility-belt library 71 | for JavaScript that provides a lot of the functional programming support that 72 | you would expect ... but without extending any of the built-in JavaScript 73 | objects." It's especially great for achieving list comprehension-like things 74 | in JavaScript. 75 | 76 | *jQuery* has many strengths, two of which we will take advantage of here either 77 | directly or indirectly through *Backbone.js*: 78 | 79 | 1. DOM selection and manipulation (easily finding and modifying elements on the 80 | page), and 81 | 2. Ajax handling (making asynchronous requests to the server without a page 82 | refresh) 83 | 84 | .. _Backbone.js: http://backbonejs.org/ 85 | .. _Underscore.js: http://underscorejs.org/ 86 | .. _jQuery: http://jquery.com/ 87 | 88 | Downloading the Libraries 89 | ------------------------- 90 | 91 | So let's go ahead and download each of these into our project (NOTE: If you 92 | prefer, you can use a CDN such as `cdnjs `_. If you do not use a 93 | CDN, you should use a merger and minifier to combine and compress your assets. 94 | Django-compressor is a good one to consider). First, create a reasonable 95 | structure for your static assets. I like to create ``libs`` folders for 3rd- 96 | party assets, and an additional folder for app-specific assets (we'll come back 97 | to that later):: 98 | 99 | mkdir static 100 | cd static 101 | mkdir libs polls 102 | 103 | Remember to add your *static* folder to the ``STATICFILES_DIRS`` setting, if it 104 | is not within an app directory. 105 | 106 | When downloading the 3rd-party libraries remember, ``wget`` is your friend:: 107 | 108 | cd libs 109 | wget http://underscorejs.org/underscore.js 110 | wget http://backbonejs.org/backbone.js 111 | wget http://code.jquery.com/jquery-1.8.0.js -O jquery.js 112 | 113 | Automated Testing 114 | ~~~~~~~~~~~~~~~~~ 115 | 116 | You may want to download a library for writing automated tests as well. I find 117 | `QUnit`_ to work well, and if you're familiar with xUnit testing frameworks 118 | (like the Python unittest package), then it'll make a lot of sense to you. 119 | However, some prefer *Jasmine*. 120 | 121 | To set up QUnit, first download the library:: 122 | 123 | wget http://code.jquery.com/qunit/qunit-1.9.0.js -O qunit.js 124 | wget http://code.jquery.com/qunit/qunit-1.9.0.css -O qunit.css 125 | 126 | Then set up a test template: 127 | 128 | *templates/test/index.html*:: 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 141 | 142 | 143 | 144 |
145 | 146 | 149 | 150 | 151 | 152 | 153 | 154 | .. _QUnit: http://qunitjs.com/ 155 | 156 | 157 | Setting Up the Templates 158 | ------------------------ 159 | 160 | In the interest of simplicity, the ``polls`` tutorial omits the HTML 161 | scaffolding from its templates. It is going to be in our interest to include 162 | this scaffolding. Let's create a super-simple base template for our app. 163 | 164 | *templates/polls/base.html*:: 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | {% block content %} 175 | {% endblock %} 176 | 177 | 178 | 179 | Next, modify each of *index.html*, *detail.html*, and *results.html* to extend 180 | the base. Though we will be creating a single-page app, we will still be using 181 | each of these templates:: 182 | 183 | {% extend "polls/base.html" %} 184 | 185 | {% block content %} 186 | [...original template content...] 187 | {% endblock %} 188 | 189 | Now we're ready to start with Backbone! 190 | 191 | 192 | Exposing an API 193 | =============== 194 | 195 | For something simple and low-security like this polling app, we may not really 196 | need a full-featured API framework, but we'll use one anyway, for demonstration. 197 | Every so often someone writes a good roundup of the options in this regard on 198 | their blog, on some mailing list, or on Stack Overflow. The most recent good one 199 | that I've come across is on Daniel Greenfield's (`@pydanny`_) post `Choosing an 200 | API framework for Django`_. Danny recommends TastyPie and Django REST Framework. 201 | 202 | We'll use Django REST Framework (DRF), but keep it as simple as we can. First, 203 | install DRF using the `install instructions`_ on Read the Docs. Now create an 204 | app for the API called ``polls_api``. In the ``polls_api.views`` module, 205 | enter the following:: 206 | 207 | from django.shortcuts import get_object_or_404 208 | from djangorestframework import views 209 | from polls.models import Poll 210 | 211 | class PollResults (views.View): 212 | 213 | def get(self, request, poll_id): 214 | poll = get_object_or_404(Poll.objects.all(), pk=poll_id) 215 | results = { 216 | 'question': poll.question, 217 | 'choices': [{ 218 | 'id': choice.id, 219 | 'choice': choice.choice, 220 | 'votes': choice.votes 221 | } for choice in poll.choice_set.all()] 222 | } 223 | return results 224 | 225 | poll_results_view = PollResults.as_view() 226 | 227 | Let's break this down. Django REST Framework uses an interface similar to 228 | Django's core `class-based views`_. Here we define a view class that supports 229 | one HTTP method: GET. 230 | 231 | :: 232 | 233 | ... 234 | class PollResults (views.View): 235 | 236 | def get(self, request, poll_id): 237 | ... 238 | 239 | Next, we get the requested poll object, and construct a dictionary of data that 240 | represents what we want to return to the client. 241 | 242 | :: 243 | 244 | results = { 245 | ... 246 | } 247 | return results 248 | 249 | Note that our view method then just returns this dictionary, not an 250 | HttpResponse. DRF alows us to simple return the data we want represented by the 251 | API. This data will be encoded as JSON or JSON-P or XML, ..., depending on what 252 | is requested by the client. 253 | 254 | .. _@pydanny: 255 | http://www.twitter.com/pydanny 256 | 257 | .. _Choosing an API framework for Django: 258 | http://pydanny.com/choosing-an-api-framework-for-django.html 259 | 260 | .. _install instructions: 261 | http://django-rest-framework.readthedocs.org/en/latest/#installation 262 | 263 | .. _class-based views: 264 | https://docs.djangoproject.com/en/dev/topics/class-based-views/ 265 | 266 | 267 | A11y - Hijacking References and Submissions 268 | =========================================== 269 | 270 | 271 | Client-side Templating 272 | ====================== 273 | 274 | 275 | Further Exploration 276 | =================== 277 | 278 | DRYness 279 | ------- 280 | 281 | One thing I've been experimenting with is using the same templating language on 282 | both the client and the server. I have been working on a Django template adapter 283 | for the PyBars project (`djangobars`_), with the intention of using Handlebars 284 | in both places. With Handlebars, it would be possible to still use many of 285 | Dajngo's template tags and filters in the templates. 286 | 287 | Though I like this approach, some potential downsides include: 288 | 289 | * having to implement Django's filters in Javascript as well, if I really 290 | want to use the templates without modification on both ends of the pipe 291 | 292 | .. _djangobars: https://github.com/mjumbewu/djangobars 293 | 294 | I18n 295 | ---- 296 | 297 | I've recently built support for Django's ``makemessages`` command in to 298 | `django-mustachejs`_. I find this to work pretty well. 299 | 300 | .. _django-mustachejs: https://github.com/mjumbewu/django-mustachejs 301 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjumbewu/guide-to-backbonejs-with-django/8550d43aa7196c0af4554970ca3f8ec2ca77b26f/__init__.py -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from django.core.management import execute_manager 3 | try: 4 | import settings # Assumed to be in the same directory. 5 | except ImportError: 6 | import sys 7 | sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) 8 | sys.exit(1) 9 | 10 | if __name__ == "__main__": 11 | execute_manager(settings) 12 | -------------------------------------------------------------------------------- /polls.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjumbewu/guide-to-backbonejs-with-django/8550d43aa7196c0af4554970ca3f8ec2ca77b26f/polls.db -------------------------------------------------------------------------------- /polls/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjumbewu/guide-to-backbonejs-with-django/8550d43aa7196c0af4554970ca3f8ec2ca77b26f/polls/__init__.py -------------------------------------------------------------------------------- /polls/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from polls.models import Poll, Choice 3 | 4 | 5 | class ChoiceInline(admin.TabularInline): 6 | model = Choice 7 | extra = 3 8 | 9 | 10 | class PollAdmin(admin.ModelAdmin): 11 | date_hierarchy = 'pub_date' 12 | fieldsets = [ 13 | (None, {'fields': ['question']}), 14 | ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), 15 | ] 16 | inlines = [ChoiceInline] 17 | list_display = ('question', 'pub_date', 'was_published_today') 18 | list_filter = ['pub_date'] 19 | search_fields = ['question'] 20 | 21 | 22 | admin.site.register(Poll, PollAdmin) 23 | -------------------------------------------------------------------------------- /polls/fixtures/polls_forms_testdata.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk": 1, 4 | "model": "polls.poll", 5 | "fields": { 6 | "pub_date": "2011-04-09 23:44:02", 7 | "question": "Are you learning about testing in Django?" 8 | } 9 | }, 10 | { 11 | "pk": 2, 12 | "model": "polls.poll", 13 | "fields": { 14 | "pub_date": "2011-04-16 14:42:52", 15 | "question": "How do you feel today?" 16 | } 17 | }, 18 | { 19 | "pk": 1, 20 | "model": "polls.choice", 21 | "fields": { 22 | "votes": 1, 23 | "poll": 1, 24 | "choice": "Yes" 25 | } 26 | }, 27 | { 28 | "pk": 2, 29 | "model": "polls.choice", 30 | "fields": { 31 | "votes": 0, 32 | "poll": 1, 33 | "choice": "No" 34 | } 35 | }, 36 | { 37 | "pk": 3, 38 | "model": "polls.choice", 39 | "fields": { 40 | "votes": 1, 41 | "poll": 2, 42 | "choice": "Alright." 43 | } 44 | }, 45 | { 46 | "pk": 4, 47 | "model": "polls.choice", 48 | "fields": { 49 | "votes": 0, 50 | "poll": 2, 51 | "choice": "Meh." 52 | } 53 | }, 54 | { 55 | "pk": 5, 56 | "model": "polls.choice", 57 | "fields": { 58 | "votes": 0, 59 | "poll": 2, 60 | "choice": "Not so good." 61 | } 62 | } 63 | ] -------------------------------------------------------------------------------- /polls/fixtures/polls_views_testdata.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk": 1, 4 | "model": "polls.poll", 5 | "fields": { 6 | "pub_date": "2011-04-09 23:44:02", 7 | "question": "Are you learning about testing in Django?" 8 | } 9 | }, 10 | { 11 | "pk": 2, 12 | "model": "polls.poll", 13 | "fields": { 14 | "pub_date": "2031-04-09 23:44:02", 15 | "question": "IT'S THE FUTURE..." 16 | } 17 | }, 18 | { 19 | "pk": 1, 20 | "model": "polls.choice", 21 | "fields": { 22 | "votes": 1, 23 | "poll": 1, 24 | "choice": "Yes" 25 | } 26 | }, 27 | { 28 | "pk": 2, 29 | "model": "polls.choice", 30 | "fields": { 31 | "votes": 0, 32 | "poll": 1, 33 | "choice": "No" 34 | } 35 | } 36 | ] -------------------------------------------------------------------------------- /polls/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from polls.models import Choice 3 | 4 | 5 | class PollForm(forms.Form): 6 | def __init__(self, *args, **kwargs): 7 | # We require an ``instance`` parameter. 8 | self.instance = kwargs.pop('instance') 9 | 10 | # We call ``super`` (without the ``instance`` param) to finish 11 | # off the setup. 12 | super(PollForm, self).__init__(*args, **kwargs) 13 | 14 | # We add on a ``choice`` field based on the instance we've got. 15 | # This has to be done here (instead of declaratively) because the 16 | # ``Poll`` instance will change from request to request. 17 | self.fields['choice'] = forms.ModelChoiceField(queryset=Choice.objects.filter(poll=self.instance.pk), empty_label=None, widget=forms.RadioSelect) 18 | 19 | def save(self): 20 | if not self.is_valid(): 21 | raise forms.ValidationError("PollForm was not validated first before trying to call 'save'.") 22 | 23 | choice = self.cleaned_data['choice'] 24 | choice.record_vote() 25 | return choice 26 | -------------------------------------------------------------------------------- /polls/models.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from django.db import models 3 | 4 | 5 | class PollManager(models.Manager): 6 | def get_query_set(self): 7 | now = datetime.datetime.now() 8 | return super(PollManager, self).get_query_set().filter(pub_date__lte=now) 9 | 10 | 11 | class Poll(models.Model): 12 | question = models.CharField(max_length=200) 13 | pub_date = models.DateTimeField('date published', default=datetime.datetime.now) 14 | 15 | objects = models.Manager() 16 | published = PollManager() 17 | 18 | def __unicode__(self): 19 | return self.question 20 | 21 | def was_published_today(self): 22 | return self.pub_date.date() == datetime.date.today() 23 | was_published_today.short_description = 'Published today?' 24 | 25 | 26 | class Choice(models.Model): 27 | poll = models.ForeignKey(Poll) 28 | choice = models.CharField(max_length=200) 29 | votes = models.IntegerField(default=0) 30 | 31 | def __unicode__(self): 32 | return self.choice 33 | 34 | def record_vote(self): 35 | self.votes += 1 36 | self.save() 37 | -------------------------------------------------------------------------------- /polls/tests/__init__.py: -------------------------------------------------------------------------------- 1 | from polls.tests.forms import * 2 | from polls.tests.models import * 3 | from polls.tests.views import * 4 | -------------------------------------------------------------------------------- /polls/tests/forms.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from polls.forms import PollForm 3 | from polls.models import Poll, Choice 4 | 5 | 6 | class PollFormTestCase(TestCase): 7 | fixtures = ['polls_forms_testdata.json'] 8 | 9 | def setUp(self): 10 | super(PollFormTestCase, self).setUp() 11 | self.poll_1 = Poll.objects.get(pk=1) 12 | self.poll_2 = Poll.objects.get(pk=2) 13 | 14 | def test_init(self): 15 | # Test successful init without data. 16 | form = PollForm(instance=self.poll_1) 17 | self.assertTrue(isinstance(form.instance, Poll)) 18 | self.assertEqual(form.instance.pk, self.poll_1.pk) 19 | self.assertEqual([c for c in form.fields['choice'].choices], [(1, u'Yes'), (2, u'No')]) 20 | 21 | # Test successful init with data. 22 | form = PollForm({'choice': 3}, instance=self.poll_2) 23 | self.assertTrue(isinstance(form.instance, Poll)) 24 | self.assertEqual(form.instance.pk, self.poll_2.pk) 25 | self.assertEqual([c for c in form.fields['choice'].choices], [(3, u'Alright.'), (4, u'Meh.'), (5, u'Not so good.')]) 26 | 27 | # Test a failed init without data. 28 | self.assertRaises(KeyError, PollForm) 29 | 30 | # Test a failed init with data. 31 | self.assertRaises(KeyError, PollForm, {}) 32 | 33 | def test_save(self): 34 | self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 1) 35 | self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 0) 36 | 37 | # Test the first choice. 38 | form_1 = PollForm({'choice': 1}, instance=self.poll_1) 39 | form_1.save() 40 | self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 2) 41 | self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 0) 42 | 43 | # Test the second choice. 44 | form_2 = PollForm({'choice': 2}, instance=self.poll_1) 45 | form_2.save() 46 | self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 2) 47 | self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 1) 48 | 49 | # Test the other poll. 50 | self.assertEqual(self.poll_2.choice_set.get(pk=3).votes, 1) 51 | self.assertEqual(self.poll_2.choice_set.get(pk=4).votes, 0) 52 | self.assertEqual(self.poll_2.choice_set.get(pk=5).votes, 0) 53 | 54 | form_3 = PollForm({'choice': 5}, instance=self.poll_2) 55 | form_3.save() 56 | self.assertEqual(self.poll_2.choice_set.get(pk=3).votes, 1) 57 | self.assertEqual(self.poll_2.choice_set.get(pk=4).votes, 0) 58 | self.assertEqual(self.poll_2.choice_set.get(pk=5).votes, 1) 59 | -------------------------------------------------------------------------------- /polls/tests/models.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from django.test import TestCase 3 | from polls.models import Poll, Choice 4 | 5 | 6 | class PollTestCase(TestCase): 7 | fixtures = ['polls_forms_testdata.json'] 8 | 9 | def setUp(self): 10 | super(PollTestCase, self).setUp() 11 | self.poll_1 = Poll.objects.get(pk=1) 12 | self.poll_2 = Poll.objects.get(pk=2) 13 | 14 | def test_was_published_today(self): 15 | # Because unless you're timetraveling, they weren't. 16 | self.assertFalse(self.poll_1.was_published_today()) 17 | self.assertFalse(self.poll_2.was_published_today()) 18 | 19 | # Modify & check again. 20 | now = datetime.datetime.now() 21 | self.poll_1.pub_date = now 22 | self.poll_1.save() 23 | self.assertTrue(self.poll_1.was_published_today()) 24 | 25 | def test_better_defaults(self): 26 | now = datetime.datetime.now() 27 | poll = Poll.objects.create( 28 | question="A test question." 29 | ) 30 | self.assertEqual(poll.pub_date.date(), now.date()) 31 | 32 | def test_no_future_dated_polls(self): 33 | # Create the future-dated ``Poll``. 34 | poll = Poll.objects.create( 35 | question="Do we have flying cars yet?", 36 | pub_date=datetime.datetime.now() + datetime.timedelta(days=1) 37 | ) 38 | self.assertEqual(list(Poll.objects.all().values_list('id', flat=True)), [1, 2, 3]) 39 | self.assertEqual(list(Poll.published.all().values_list('id', flat=True)), [1, 2]) 40 | 41 | 42 | class ChoiceTestCase(TestCase): 43 | fixtures = ['polls_forms_testdata.json'] 44 | 45 | def test_record_vote(self): 46 | choice_1 = Choice.objects.get(pk=1) 47 | choice_2 = Choice.objects.get(pk=2) 48 | 49 | self.assertEqual(Choice.objects.get(pk=1).votes, 1) 50 | self.assertEqual(Choice.objects.get(pk=2).votes, 0) 51 | 52 | choice_1.record_vote() 53 | self.assertEqual(Choice.objects.get(pk=1).votes, 2) 54 | self.assertEqual(Choice.objects.get(pk=2).votes, 0) 55 | 56 | choice_2.record_vote() 57 | self.assertEqual(Choice.objects.get(pk=1).votes, 2) 58 | self.assertEqual(Choice.objects.get(pk=2).votes, 1) 59 | 60 | choice_1.record_vote() 61 | self.assertEqual(Choice.objects.get(pk=1).votes, 3) 62 | self.assertEqual(Choice.objects.get(pk=2).votes, 1) 63 | 64 | def test_better_defaults(self): 65 | poll = Poll.objects.create( 66 | question="Are you still there?" 67 | ) 68 | choice = Choice.objects.create( 69 | poll=poll, 70 | choice="I don't blame you." 71 | ) 72 | 73 | self.assertEqual(poll.choice_set.all()[0].choice, "I don't blame you.") 74 | self.assertEqual(poll.choice_set.all()[0].votes, 0) 75 | -------------------------------------------------------------------------------- /polls/tests/views.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from django.core.urlresolvers import reverse 3 | from django.test import TestCase 4 | from polls.models import Poll, Choice 5 | 6 | 7 | class PollsViewsTestCase(TestCase): 8 | fixtures = ['polls_views_testdata.json'] 9 | 10 | def test_index(self): 11 | resp = self.client.get(reverse('polls_index')) 12 | self.assertEqual(resp.status_code, 200) 13 | self.assertTrue('latest_poll_list' in resp.context) 14 | self.assertEqual([poll.pk for poll in resp.context['latest_poll_list']], [1]) 15 | poll_1 = resp.context['latest_poll_list'][0] 16 | self.assertEqual(poll_1.question, 'Are you learning about testing in Django?') 17 | self.assertEqual(poll_1.choice_set.count(), 2) 18 | choices = poll_1.choice_set.all() 19 | self.assertEqual(choices[0].choice, 'Yes') 20 | self.assertEqual(choices[0].votes, 1) 21 | self.assertEqual(choices[1].choice, 'No') 22 | self.assertEqual(choices[1].votes, 0) 23 | 24 | def test_detail(self): 25 | resp = self.client.get(reverse('polls_detail', kwargs={'poll_id': 1})) 26 | self.assertEqual(resp.status_code, 200) 27 | self.assertEqual(resp.context['poll'].pk, 1) 28 | self.assertEqual(resp.context['poll'].question, 'Are you learning about testing in Django?') 29 | 30 | # Ensure that non-existent polls throw a 404. 31 | resp = self.client.get(reverse('polls_detail', kwargs={'poll_id': 2})) 32 | self.assertEqual(resp.status_code, 404) 33 | 34 | def test_results(self): 35 | resp = self.client.get(reverse('polls_results', kwargs={'poll_id': 1})) 36 | self.assertEqual(resp.status_code, 200) 37 | self.assertEqual(resp.context['poll'].pk, 1) 38 | self.assertEqual(resp.context['poll'].question, 'Are you learning about testing in Django?') 39 | 40 | # Ensure that non-existent polls throw a 404. 41 | resp = self.client.get(reverse('polls_results', kwargs={'poll_id': 2})) 42 | self.assertEqual(resp.status_code, 404) 43 | 44 | def test_good_vote(self): 45 | poll_1 = Poll.objects.get(pk=1) 46 | self.assertEqual(poll_1.choice_set.get(pk=1).votes, 1) 47 | 48 | resp = self.client.post(reverse('polls_detail', kwargs={'poll_id': 1}), {'choice': 1}) 49 | self.assertEqual(resp.status_code, 302) 50 | self.assertEqual(resp['Location'], 'http://testserver/polls/1/results/') 51 | 52 | self.assertEqual(poll_1.choice_set.get(pk=1).votes, 2) 53 | 54 | def test_bad_votes(self): 55 | # Ensure a non-existant PK throws a Not Found. 56 | resp = self.client.post(reverse('polls_detail', kwargs={'poll_id': 1000000})) 57 | self.assertEqual(resp.status_code, 404) 58 | 59 | # Sanity check. 60 | poll_1 = Poll.objects.get(pk=1) 61 | self.assertEqual(poll_1.choice_set.get(pk=1).votes, 1) 62 | 63 | # Send no POST data. 64 | resp = self.client.post(reverse('polls_detail', kwargs={'poll_id': 1})) 65 | self.assertEqual(resp.status_code, 200) 66 | self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.']) 67 | 68 | # Send junk POST data. 69 | resp = self.client.post(reverse('polls_detail', kwargs={'poll_id': 1}), {'foo': 'bar'}) 70 | self.assertEqual(resp.status_code, 200) 71 | self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.']) 72 | 73 | # Send a non-existant Choice PK. 74 | resp = self.client.post(reverse('polls_detail', kwargs={'poll_id': 1}), {'choice': 300}) 75 | self.assertEqual(resp.status_code, 200) 76 | self.assertEqual(resp.context['form']['choice'].errors, [u'Select a valid choice. That choice is not one of the available choices.']) 77 | -------------------------------------------------------------------------------- /polls/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | 3 | 4 | urlpatterns = patterns('polls.views', 5 | url(r'^$', 'index', name='polls_index'), 6 | url(r'^(?P\d+)/$', 'detail', name='polls_detail'), 7 | url(r'^(?P\d+)/results/$', 'results', name='polls_results'), 8 | ) 9 | -------------------------------------------------------------------------------- /polls/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | from django.core.urlresolvers import reverse 3 | from django.http import HttpResponseRedirect, HttpResponse 4 | from django.shortcuts import render_to_response, get_object_or_404 5 | from django.template import RequestContext 6 | from polls.forms import PollForm 7 | from polls.models import Poll, Choice 8 | from polls_api.resources import PollResource 9 | 10 | 11 | def index(request): 12 | latest_poll_list = Poll.published.all().order_by('-pub_date')[:5] 13 | return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) 14 | 15 | 16 | def detail(request, poll_id): 17 | p = get_object_or_404(Poll.published.all(), pk=poll_id) 18 | 19 | if request.method == 'POST': 20 | form = PollForm(request.POST, instance=p) 21 | 22 | if form.is_valid(): 23 | form.save() 24 | return HttpResponseRedirect(reverse('polls_results', kwargs={'poll_id': p.id})) 25 | else: 26 | form = PollForm(instance=p) 27 | 28 | initial_results_data = PollResource().serialize(p) 29 | 30 | return render_to_response('polls/detail.html', { 31 | 'poll': p, 32 | 'form': form, 33 | 'initial_results_data': json.dumps(initial_results_data) 34 | }, context_instance=RequestContext(request)) 35 | 36 | 37 | def results(request, poll_id): 38 | p = get_object_or_404(Poll.published.all(), pk=poll_id) 39 | return render_to_response('polls/results.html', {'poll': p}, 40 | context_instance=RequestContext(request)) 41 | -------------------------------------------------------------------------------- /polls_api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjumbewu/guide-to-backbonejs-with-django/8550d43aa7196c0af4554970ca3f8ec2ca77b26f/polls_api/__init__.py -------------------------------------------------------------------------------- /polls_api/resources.py: -------------------------------------------------------------------------------- 1 | from djangorestframework import resources 2 | from polls.models import Poll 3 | 4 | class PollResource (resources.ModelResource): 5 | model = Poll 6 | fields = ('id', 'question', 'choices') 7 | exclude = () 8 | 9 | def choices(self, poll): 10 | return [{ 11 | 'id': choice.id, 12 | 'choice': choice.choice, 13 | 'votes': choice.votes 14 | } for choice in poll.choice_set.all()] 15 | -------------------------------------------------------------------------------- /polls_api/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | 3 | 4 | urlpatterns = patterns('polls_api.views', 5 | url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework')), 6 | url(r'^(?P\d+)/$', 'poll_results_view', name='polls_api_results'), 7 | url(r'^(?P\d+)/votes/$', 'poll_votes_view', name='polls_api_votes'), 8 | ) 9 | -------------------------------------------------------------------------------- /polls_api/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import get_object_or_404 2 | from django.core.urlresolvers import reverse 3 | from djangorestframework import views 4 | from djangorestframework.response import Response 5 | from polls.forms import PollForm 6 | from polls.models import Poll 7 | from .resources import PollResource 8 | 9 | class PollResults (views.View): 10 | 11 | def get(self, request, poll_id): 12 | poll = get_object_or_404(Poll.objects.all(), pk=poll_id) 13 | results = PollResource().serialize(poll) 14 | return results 15 | 16 | 17 | class PollVotes (views.View): 18 | 19 | def post(self, request, poll_id): 20 | poll = get_object_or_404(Poll.objects.all(), pk=poll_id) 21 | form = PollForm(request.POST, instance=poll) 22 | 23 | if form.is_valid(): 24 | form.save() 25 | else: 26 | return Response(content=form.errors, status=400) 27 | 28 | return Response(status=303, headers={'Location': reverse('polls_api_results', args=[poll_id])}) 29 | 30 | poll_results_view = PollResults.as_view() 31 | poll_votes_view = PollVotes.as_view() 32 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==1.4.1 2 | djangorestframework==0.4.0 3 | psycopg2 4 | dj-database-url 5 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | # Django settings for guide_to_testing project. 2 | 3 | DEBUG = True 4 | TEMPLATE_DEBUG = DEBUG 5 | 6 | ADMINS = ( 7 | # ('Your Name', 'your_email@example.com'), 8 | ) 9 | 10 | MANAGERS = ADMINS 11 | 12 | DATABASES = { 13 | 'default': { 14 | 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 15 | 'NAME': 'polls.db', # Or path to database file if using sqlite3. 16 | 'USER': '', # Not used with sqlite3. 17 | 'PASSWORD': '', # Not used with sqlite3. 18 | 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 19 | 'PORT': '', # Set to empty string for default. Not used with sqlite3. 20 | } 21 | } 22 | 23 | # Local time zone for this installation. Choices can be found here: 24 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 25 | # although not all choices may be available on all operating systems. 26 | # On Unix systems, a value of None will cause Django to use the same 27 | # timezone as the operating system. 28 | # If running in a Windows environment this must be set to the same as your 29 | # system time zone. 30 | TIME_ZONE = 'America/Chicago' 31 | 32 | # Language code for this installation. All choices can be found here: 33 | # http://www.i18nguy.com/unicode/language-identifiers.html 34 | LANGUAGE_CODE = 'en-us' 35 | 36 | SITE_ID = 1 37 | 38 | # If you set this to False, Django will make some optimizations so as not 39 | # to load the internationalization machinery. 40 | USE_I18N = True 41 | 42 | # If you set this to False, Django will not format dates, numbers and 43 | # calendars according to the current locale 44 | USE_L10N = True 45 | 46 | # Absolute filesystem path to the directory that will hold user-uploaded files. 47 | # Example: "/home/media/media.lawrence.com/media/" 48 | MEDIA_ROOT = '' 49 | 50 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 51 | # trailing slash if there is a path component (optional in other cases). 52 | # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" 53 | MEDIA_URL = '' 54 | 55 | # Absolute path to the directory that holds static files. 56 | # Example: "/home/media/media.lawrence.com/static/" 57 | STATIC_ROOT = '' 58 | 59 | # URL that handles the static files served from STATIC_ROOT. 60 | # Example: "http://media.lawrence.com/static/" 61 | STATIC_URL = '/static/' 62 | 63 | # URL prefix for admin media -- CSS, JavaScript and images. 64 | # Make sure to use a trailing slash. 65 | # Examples: "http://foo.com/static/admin/", "/static/admin/". 66 | ADMIN_MEDIA_PREFIX = '/static/admin/' 67 | 68 | import os 69 | PROJECT_ROOT = os.path.dirname(__file__) 70 | 71 | # A list of locations of additional static files 72 | STATICFILES_DIRS = ( 73 | os.path.join(PROJECT_ROOT, 'static'), 74 | ) 75 | # List of finder classes that know how to find static files in 76 | # various locations. 77 | STATICFILES_FINDERS = ( 78 | 'django.contrib.staticfiles.finders.FileSystemFinder', 79 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 80 | # 'django.contrib.staticfiles.finders.DefaultStorageFinder', 81 | ) 82 | 83 | # Make this unique, and don't share it with anybody. 84 | SECRET_KEY = 'p(u%@fn&r_d7@$p@jqfwwp#$l-@=_pdf_$y$2jztv_dmcgk@g5' 85 | 86 | # List of callables that know how to import templates from various sources. 87 | TEMPLATE_LOADERS = ( 88 | 'django.template.loaders.filesystem.Loader', 89 | 'django.template.loaders.app_directories.Loader', 90 | # 'django.template.loaders.eggs.Loader', 91 | ) 92 | 93 | MIDDLEWARE_CLASSES = ( 94 | 'django.middleware.common.CommonMiddleware', 95 | 'django.contrib.sessions.middleware.SessionMiddleware', 96 | 'django.middleware.csrf.CsrfViewMiddleware', 97 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 98 | 'django.contrib.messages.middleware.MessageMiddleware', 99 | ) 100 | 101 | ROOT_URLCONF = 'urls' 102 | 103 | TEMPLATE_DIRS = ( 104 | # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 105 | # Always use forward slashes, even on Windows. 106 | # Don't forget to use absolute paths, not relative paths. 107 | os.path.join(PROJECT_ROOT, 'templates'), 108 | ) 109 | 110 | INSTALLED_APPS = ( 111 | 'django.contrib.auth', 112 | 'django.contrib.contenttypes', 113 | 'django.contrib.sessions', 114 | 'django.contrib.sites', 115 | 'django.contrib.messages', 116 | 'django.contrib.staticfiles', 117 | 'django.contrib.admin', 118 | 'django.contrib.admindocs', 119 | 120 | 'djangorestframework', 121 | 'polls', 122 | ) 123 | 124 | # A sample logging configuration. The only tangible logging 125 | # performed by this configuration is to send an email to 126 | # the site admins on every HTTP 500 error. 127 | # See http://docs.djangoproject.com/en/dev/topics/logging for 128 | # more details on how to customize your logging configuration. 129 | LOGGING = { 130 | 'version': 1, 131 | 'disable_existing_loggers': False, 132 | 'handlers': { 133 | 'mail_admins': { 134 | 'level': 'ERROR', 135 | 'class': 'django.utils.log.AdminEmailHandler' 136 | } 137 | }, 138 | 'loggers': { 139 | 'django.request':{ 140 | 'handlers': ['mail_admins'], 141 | 'level': 'ERROR', 142 | 'propagate': True, 143 | }, 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /static/libs/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 0.9.2 2 | 3 | // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | 8 | (function(){ 9 | 10 | // Initial Setup 11 | // ------------- 12 | 13 | // Save a reference to the global object (`window` in the browser, `global` 14 | // on the server). 15 | var root = this; 16 | 17 | // Save the previous value of the `Backbone` variable, so that it can be 18 | // restored later on, if `noConflict` is used. 19 | var previousBackbone = root.Backbone; 20 | 21 | // Create a local reference to slice/splice. 22 | var slice = Array.prototype.slice; 23 | var splice = Array.prototype.splice; 24 | 25 | // The top-level namespace. All public Backbone classes and modules will 26 | // be attached to this. Exported for both CommonJS and the browser. 27 | var Backbone; 28 | if (typeof exports !== 'undefined') { 29 | Backbone = exports; 30 | } else { 31 | Backbone = root.Backbone = {}; 32 | } 33 | 34 | // Current version of the library. Keep in sync with `package.json`. 35 | Backbone.VERSION = '0.9.2'; 36 | 37 | // Require Underscore, if we're on the server, and it's not already present. 38 | var _ = root._; 39 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); 40 | 41 | // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. 42 | var $ = root.jQuery || root.Zepto || root.ender; 43 | 44 | // Set the JavaScript library that will be used for DOM manipulation and 45 | // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery, 46 | // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an 47 | // alternate JavaScript library (or a mock library for testing your views 48 | // outside of a browser). 49 | Backbone.setDomLibrary = function(lib) { 50 | $ = lib; 51 | }; 52 | 53 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 54 | // to its previous owner. Returns a reference to this Backbone object. 55 | Backbone.noConflict = function() { 56 | root.Backbone = previousBackbone; 57 | return this; 58 | }; 59 | 60 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option 61 | // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and 62 | // set a `X-Http-Method-Override` header. 63 | Backbone.emulateHTTP = false; 64 | 65 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 66 | // `application/json` requests ... will encode the body as 67 | // `application/x-www-form-urlencoded` instead and will send the model in a 68 | // form param named `model`. 69 | Backbone.emulateJSON = false; 70 | 71 | // Backbone.Events 72 | // ----------------- 73 | 74 | // Regular expression used to split event strings 75 | var eventSplitter = /\s+/; 76 | 77 | // A module that can be mixed in to *any object* in order to provide it with 78 | // custom events. You may bind with `on` or remove with `off` callback functions 79 | // to an event; trigger`-ing an event fires all callbacks in succession. 80 | // 81 | // var object = {}; 82 | // _.extend(object, Backbone.Events); 83 | // object.on('expand', function(){ alert('expanded'); }); 84 | // object.trigger('expand'); 85 | // 86 | var Events = Backbone.Events = { 87 | 88 | // Bind one or more space separated events, `events`, to a `callback` 89 | // function. Passing `"all"` will bind the callback to all events fired. 90 | on: function(events, callback, context) { 91 | 92 | var calls, event, node, tail, list; 93 | if (!callback) return this; 94 | events = events.split(eventSplitter); 95 | calls = this._callbacks || (this._callbacks = {}); 96 | 97 | // Create an immutable callback list, allowing traversal during 98 | // modification. The tail is an empty object that will always be used 99 | // as the next node. 100 | while (event = events.shift()) { 101 | list = calls[event]; 102 | node = list ? list.tail : {}; 103 | node.next = tail = {}; 104 | node.context = context; 105 | node.callback = callback; 106 | calls[event] = {tail: tail, next: list ? list.next : node}; 107 | } 108 | 109 | return this; 110 | }, 111 | 112 | // Remove one or many callbacks. If `context` is null, removes all callbacks 113 | // with that function. If `callback` is null, removes all callbacks for the 114 | // event. If `events` is null, removes all bound callbacks for all events. 115 | off: function(events, callback, context) { 116 | var event, calls, node, tail, cb, ctx; 117 | 118 | // No events, or removing *all* events. 119 | if (!(calls = this._callbacks)) return; 120 | if (!(events || callback || context)) { 121 | delete this._callbacks; 122 | return this; 123 | } 124 | 125 | // Loop through the listed events and contexts, splicing them out of the 126 | // linked list of callbacks if appropriate. 127 | events = events ? events.split(eventSplitter) : _.keys(calls); 128 | while (event = events.shift()) { 129 | node = calls[event]; 130 | delete calls[event]; 131 | if (!node || !(callback || context)) continue; 132 | // Create a new list, omitting the indicated callbacks. 133 | tail = node.tail; 134 | while ((node = node.next) !== tail) { 135 | cb = node.callback; 136 | ctx = node.context; 137 | if ((callback && cb !== callback) || (context && ctx !== context)) { 138 | this.on(event, cb, ctx); 139 | } 140 | } 141 | } 142 | 143 | return this; 144 | }, 145 | 146 | // Trigger one or many events, firing all bound callbacks. Callbacks are 147 | // passed the same arguments as `trigger` is, apart from the event name 148 | // (unless you're listening on `"all"`, which will cause your callback to 149 | // receive the true name of the event as the first argument). 150 | trigger: function(events) { 151 | var event, node, calls, tail, args, all, rest; 152 | if (!(calls = this._callbacks)) return this; 153 | all = calls.all; 154 | events = events.split(eventSplitter); 155 | rest = slice.call(arguments, 1); 156 | 157 | // For each event, walk through the linked list of callbacks twice, 158 | // first to trigger the event, then to trigger any `"all"` callbacks. 159 | while (event = events.shift()) { 160 | if (node = calls[event]) { 161 | tail = node.tail; 162 | while ((node = node.next) !== tail) { 163 | node.callback.apply(node.context || this, rest); 164 | } 165 | } 166 | if (node = all) { 167 | tail = node.tail; 168 | args = [event].concat(rest); 169 | while ((node = node.next) !== tail) { 170 | node.callback.apply(node.context || this, args); 171 | } 172 | } 173 | } 174 | 175 | return this; 176 | } 177 | 178 | }; 179 | 180 | // Aliases for backwards compatibility. 181 | Events.bind = Events.on; 182 | Events.unbind = Events.off; 183 | 184 | // Backbone.Model 185 | // -------------- 186 | 187 | // Create a new model, with defined attributes. A client id (`cid`) 188 | // is automatically generated and assigned for you. 189 | var Model = Backbone.Model = function(attributes, options) { 190 | var defaults; 191 | attributes || (attributes = {}); 192 | if (options && options.parse) attributes = this.parse(attributes); 193 | if (defaults = getValue(this, 'defaults')) { 194 | attributes = _.extend({}, defaults, attributes); 195 | } 196 | if (options && options.collection) this.collection = options.collection; 197 | this.attributes = {}; 198 | this._escapedAttributes = {}; 199 | this.cid = _.uniqueId('c'); 200 | this.changed = {}; 201 | this._silent = {}; 202 | this._pending = {}; 203 | this.set(attributes, {silent: true}); 204 | // Reset change tracking. 205 | this.changed = {}; 206 | this._silent = {}; 207 | this._pending = {}; 208 | this._previousAttributes = _.clone(this.attributes); 209 | this.initialize.apply(this, arguments); 210 | }; 211 | 212 | // Attach all inheritable methods to the Model prototype. 213 | _.extend(Model.prototype, Events, { 214 | 215 | // A hash of attributes whose current and previous value differ. 216 | changed: null, 217 | 218 | // A hash of attributes that have silently changed since the last time 219 | // `change` was called. Will become pending attributes on the next call. 220 | _silent: null, 221 | 222 | // A hash of attributes that have changed since the last `'change'` event 223 | // began. 224 | _pending: null, 225 | 226 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 227 | // CouchDB users may want to set this to `"_id"`. 228 | idAttribute: 'id', 229 | 230 | // Initialize is an empty function by default. Override it with your own 231 | // initialization logic. 232 | initialize: function(){}, 233 | 234 | // Return a copy of the model's `attributes` object. 235 | toJSON: function(options) { 236 | return _.clone(this.attributes); 237 | }, 238 | 239 | // Get the value of an attribute. 240 | get: function(attr) { 241 | return this.attributes[attr]; 242 | }, 243 | 244 | // Get the HTML-escaped value of an attribute. 245 | escape: function(attr) { 246 | var html; 247 | if (html = this._escapedAttributes[attr]) return html; 248 | var val = this.get(attr); 249 | return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); 250 | }, 251 | 252 | // Returns `true` if the attribute contains a value that is not null 253 | // or undefined. 254 | has: function(attr) { 255 | return this.get(attr) != null; 256 | }, 257 | 258 | // Set a hash of model attributes on the object, firing `"change"` unless 259 | // you choose to silence it. 260 | set: function(key, value, options) { 261 | var attrs, attr, val; 262 | 263 | // Handle both `"key", value` and `{key: value}` -style arguments. 264 | if (_.isObject(key) || key == null) { 265 | attrs = key; 266 | options = value; 267 | } else { 268 | attrs = {}; 269 | attrs[key] = value; 270 | } 271 | 272 | // Extract attributes and options. 273 | options || (options = {}); 274 | if (!attrs) return this; 275 | if (attrs instanceof Model) attrs = attrs.attributes; 276 | if (options.unset) for (attr in attrs) attrs[attr] = void 0; 277 | 278 | // Run validation. 279 | if (!this._validate(attrs, options)) return false; 280 | 281 | // Check for changes of `id`. 282 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 283 | 284 | var changes = options.changes = {}; 285 | var now = this.attributes; 286 | var escaped = this._escapedAttributes; 287 | var prev = this._previousAttributes || {}; 288 | 289 | // For each `set` attribute... 290 | for (attr in attrs) { 291 | val = attrs[attr]; 292 | 293 | // If the new and current value differ, record the change. 294 | if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { 295 | delete escaped[attr]; 296 | (options.silent ? this._silent : changes)[attr] = true; 297 | } 298 | 299 | // Update or delete the current value. 300 | options.unset ? delete now[attr] : now[attr] = val; 301 | 302 | // If the new and previous value differ, record the change. If not, 303 | // then remove changes for this attribute. 304 | if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { 305 | this.changed[attr] = val; 306 | if (!options.silent) this._pending[attr] = true; 307 | } else { 308 | delete this.changed[attr]; 309 | delete this._pending[attr]; 310 | } 311 | } 312 | 313 | // Fire the `"change"` events. 314 | if (!options.silent) this.change(options); 315 | return this; 316 | }, 317 | 318 | // Remove an attribute from the model, firing `"change"` unless you choose 319 | // to silence it. `unset` is a noop if the attribute doesn't exist. 320 | unset: function(attr, options) { 321 | (options || (options = {})).unset = true; 322 | return this.set(attr, null, options); 323 | }, 324 | 325 | // Clear all attributes on the model, firing `"change"` unless you choose 326 | // to silence it. 327 | clear: function(options) { 328 | (options || (options = {})).unset = true; 329 | return this.set(_.clone(this.attributes), options); 330 | }, 331 | 332 | // Fetch the model from the server. If the server's representation of the 333 | // model differs from its current attributes, they will be overriden, 334 | // triggering a `"change"` event. 335 | fetch: function(options) { 336 | options = options ? _.clone(options) : {}; 337 | var model = this; 338 | var success = options.success; 339 | options.success = function(resp, status, xhr) { 340 | if (!model.set(model.parse(resp, xhr), options)) return false; 341 | if (success) success(model, resp); 342 | }; 343 | options.error = Backbone.wrapError(options.error, model, options); 344 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 345 | }, 346 | 347 | // Set a hash of model attributes, and sync the model to the server. 348 | // If the server returns an attributes hash that differs, the model's 349 | // state will be `set` again. 350 | save: function(key, value, options) { 351 | var attrs, current; 352 | 353 | // Handle both `("key", value)` and `({key: value})` -style calls. 354 | if (_.isObject(key) || key == null) { 355 | attrs = key; 356 | options = value; 357 | } else { 358 | attrs = {}; 359 | attrs[key] = value; 360 | } 361 | options = options ? _.clone(options) : {}; 362 | 363 | // If we're "wait"-ing to set changed attributes, validate early. 364 | if (options.wait) { 365 | if (!this._validate(attrs, options)) return false; 366 | current = _.clone(this.attributes); 367 | } 368 | 369 | // Regular saves `set` attributes before persisting to the server. 370 | var silentOptions = _.extend({}, options, {silent: true}); 371 | if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { 372 | return false; 373 | } 374 | 375 | // After a successful server-side save, the client is (optionally) 376 | // updated with the server-side state. 377 | var model = this; 378 | var success = options.success; 379 | options.success = function(resp, status, xhr) { 380 | var serverAttrs = model.parse(resp, xhr); 381 | if (options.wait) { 382 | delete options.wait; 383 | serverAttrs = _.extend(attrs || {}, serverAttrs); 384 | } 385 | if (!model.set(serverAttrs, options)) return false; 386 | if (success) { 387 | success(model, resp); 388 | } else { 389 | model.trigger('sync', model, resp, options); 390 | } 391 | }; 392 | 393 | // Finish configuring and sending the Ajax request. 394 | options.error = Backbone.wrapError(options.error, model, options); 395 | var method = this.isNew() ? 'create' : 'update'; 396 | var xhr = (this.sync || Backbone.sync).call(this, method, this, options); 397 | if (options.wait) this.set(current, silentOptions); 398 | return xhr; 399 | }, 400 | 401 | // Destroy this model on the server if it was already persisted. 402 | // Optimistically removes the model from its collection, if it has one. 403 | // If `wait: true` is passed, waits for the server to respond before removal. 404 | destroy: function(options) { 405 | options = options ? _.clone(options) : {}; 406 | var model = this; 407 | var success = options.success; 408 | 409 | var triggerDestroy = function() { 410 | model.trigger('destroy', model, model.collection, options); 411 | }; 412 | 413 | if (this.isNew()) { 414 | triggerDestroy(); 415 | return false; 416 | } 417 | 418 | options.success = function(resp) { 419 | if (options.wait) triggerDestroy(); 420 | if (success) { 421 | success(model, resp); 422 | } else { 423 | model.trigger('sync', model, resp, options); 424 | } 425 | }; 426 | 427 | options.error = Backbone.wrapError(options.error, model, options); 428 | var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); 429 | if (!options.wait) triggerDestroy(); 430 | return xhr; 431 | }, 432 | 433 | // Default URL for the model's representation on the server -- if you're 434 | // using Backbone's restful methods, override this to change the endpoint 435 | // that will be called. 436 | url: function() { 437 | var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); 438 | if (this.isNew()) return base; 439 | return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); 440 | }, 441 | 442 | // **parse** converts a response into the hash of attributes to be `set` on 443 | // the model. The default implementation is just to pass the response along. 444 | parse: function(resp, xhr) { 445 | return resp; 446 | }, 447 | 448 | // Create a new model with identical attributes to this one. 449 | clone: function() { 450 | return new this.constructor(this.attributes); 451 | }, 452 | 453 | // A model is new if it has never been saved to the server, and lacks an id. 454 | isNew: function() { 455 | return this.id == null; 456 | }, 457 | 458 | // Call this method to manually fire a `"change"` event for this model and 459 | // a `"change:attribute"` event for each changed attribute. 460 | // Calling this will cause all objects observing the model to update. 461 | change: function(options) { 462 | options || (options = {}); 463 | var changing = this._changing; 464 | this._changing = true; 465 | 466 | // Silent changes become pending changes. 467 | for (var attr in this._silent) this._pending[attr] = true; 468 | 469 | // Silent changes are triggered. 470 | var changes = _.extend({}, options.changes, this._silent); 471 | this._silent = {}; 472 | for (var attr in changes) { 473 | this.trigger('change:' + attr, this, this.get(attr), options); 474 | } 475 | if (changing) return this; 476 | 477 | // Continue firing `"change"` events while there are pending changes. 478 | while (!_.isEmpty(this._pending)) { 479 | this._pending = {}; 480 | this.trigger('change', this, options); 481 | // Pending and silent changes still remain. 482 | for (var attr in this.changed) { 483 | if (this._pending[attr] || this._silent[attr]) continue; 484 | delete this.changed[attr]; 485 | } 486 | this._previousAttributes = _.clone(this.attributes); 487 | } 488 | 489 | this._changing = false; 490 | return this; 491 | }, 492 | 493 | // Determine if the model has changed since the last `"change"` event. 494 | // If you specify an attribute name, determine if that attribute has changed. 495 | hasChanged: function(attr) { 496 | if (!arguments.length) return !_.isEmpty(this.changed); 497 | return _.has(this.changed, attr); 498 | }, 499 | 500 | // Return an object containing all the attributes that have changed, or 501 | // false if there are no changed attributes. Useful for determining what 502 | // parts of a view need to be updated and/or what attributes need to be 503 | // persisted to the server. Unset attributes will be set to undefined. 504 | // You can also pass an attributes object to diff against the model, 505 | // determining if there *would be* a change. 506 | changedAttributes: function(diff) { 507 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; 508 | var val, changed = false, old = this._previousAttributes; 509 | for (var attr in diff) { 510 | if (_.isEqual(old[attr], (val = diff[attr]))) continue; 511 | (changed || (changed = {}))[attr] = val; 512 | } 513 | return changed; 514 | }, 515 | 516 | // Get the previous value of an attribute, recorded at the time the last 517 | // `"change"` event was fired. 518 | previous: function(attr) { 519 | if (!arguments.length || !this._previousAttributes) return null; 520 | return this._previousAttributes[attr]; 521 | }, 522 | 523 | // Get all of the attributes of the model at the time of the previous 524 | // `"change"` event. 525 | previousAttributes: function() { 526 | return _.clone(this._previousAttributes); 527 | }, 528 | 529 | // Check if the model is currently in a valid state. It's only possible to 530 | // get into an *invalid* state if you're using silent changes. 531 | isValid: function() { 532 | return !this.validate(this.attributes); 533 | }, 534 | 535 | // Run validation against the next complete set of model attributes, 536 | // returning `true` if all is well. If a specific `error` callback has 537 | // been passed, call that instead of firing the general `"error"` event. 538 | _validate: function(attrs, options) { 539 | if (options.silent || !this.validate) return true; 540 | attrs = _.extend({}, this.attributes, attrs); 541 | var error = this.validate(attrs, options); 542 | if (!error) return true; 543 | if (options && options.error) { 544 | options.error(this, error, options); 545 | } else { 546 | this.trigger('error', this, error, options); 547 | } 548 | return false; 549 | } 550 | 551 | }); 552 | 553 | // Backbone.Collection 554 | // ------------------- 555 | 556 | // Provides a standard collection class for our sets of models, ordered 557 | // or unordered. If a `comparator` is specified, the Collection will maintain 558 | // its models in sort order, as they're added and removed. 559 | var Collection = Backbone.Collection = function(models, options) { 560 | options || (options = {}); 561 | if (options.model) this.model = options.model; 562 | if (options.comparator) this.comparator = options.comparator; 563 | this._reset(); 564 | this.initialize.apply(this, arguments); 565 | if (models) this.reset(models, {silent: true, parse: options.parse}); 566 | }; 567 | 568 | // Define the Collection's inheritable methods. 569 | _.extend(Collection.prototype, Events, { 570 | 571 | // The default model for a collection is just a **Backbone.Model**. 572 | // This should be overridden in most cases. 573 | model: Model, 574 | 575 | // Initialize is an empty function by default. Override it with your own 576 | // initialization logic. 577 | initialize: function(){}, 578 | 579 | // The JSON representation of a Collection is an array of the 580 | // models' attributes. 581 | toJSON: function(options) { 582 | return this.map(function(model){ return model.toJSON(options); }); 583 | }, 584 | 585 | // Add a model, or list of models to the set. Pass **silent** to avoid 586 | // firing the `add` event for every new model. 587 | add: function(models, options) { 588 | var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; 589 | options || (options = {}); 590 | models = _.isArray(models) ? models.slice() : [models]; 591 | 592 | // Begin by turning bare objects into model references, and preventing 593 | // invalid models or duplicate models from being added. 594 | for (i = 0, length = models.length; i < length; i++) { 595 | if (!(model = models[i] = this._prepareModel(models[i], options))) { 596 | throw new Error("Can't add an invalid model to a collection"); 597 | } 598 | cid = model.cid; 599 | id = model.id; 600 | if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { 601 | dups.push(i); 602 | continue; 603 | } 604 | cids[cid] = ids[id] = model; 605 | } 606 | 607 | // Remove duplicates. 608 | i = dups.length; 609 | while (i--) { 610 | models.splice(dups[i], 1); 611 | } 612 | 613 | // Listen to added models' events, and index models for lookup by 614 | // `id` and by `cid`. 615 | for (i = 0, length = models.length; i < length; i++) { 616 | (model = models[i]).on('all', this._onModelEvent, this); 617 | this._byCid[model.cid] = model; 618 | if (model.id != null) this._byId[model.id] = model; 619 | } 620 | 621 | // Insert models into the collection, re-sorting if needed, and triggering 622 | // `add` events unless silenced. 623 | this.length += length; 624 | index = options.at != null ? options.at : this.models.length; 625 | splice.apply(this.models, [index, 0].concat(models)); 626 | if (this.comparator) this.sort({silent: true}); 627 | if (options.silent) return this; 628 | for (i = 0, length = this.models.length; i < length; i++) { 629 | if (!cids[(model = this.models[i]).cid]) continue; 630 | options.index = i; 631 | model.trigger('add', model, this, options); 632 | } 633 | return this; 634 | }, 635 | 636 | // Remove a model, or a list of models from the set. Pass silent to avoid 637 | // firing the `remove` event for every model removed. 638 | remove: function(models, options) { 639 | var i, l, index, model; 640 | options || (options = {}); 641 | models = _.isArray(models) ? models.slice() : [models]; 642 | for (i = 0, l = models.length; i < l; i++) { 643 | model = this.getByCid(models[i]) || this.get(models[i]); 644 | if (!model) continue; 645 | delete this._byId[model.id]; 646 | delete this._byCid[model.cid]; 647 | index = this.indexOf(model); 648 | this.models.splice(index, 1); 649 | this.length--; 650 | if (!options.silent) { 651 | options.index = index; 652 | model.trigger('remove', model, this, options); 653 | } 654 | this._removeReference(model); 655 | } 656 | return this; 657 | }, 658 | 659 | // Add a model to the end of the collection. 660 | push: function(model, options) { 661 | model = this._prepareModel(model, options); 662 | this.add(model, options); 663 | return model; 664 | }, 665 | 666 | // Remove a model from the end of the collection. 667 | pop: function(options) { 668 | var model = this.at(this.length - 1); 669 | this.remove(model, options); 670 | return model; 671 | }, 672 | 673 | // Add a model to the beginning of the collection. 674 | unshift: function(model, options) { 675 | model = this._prepareModel(model, options); 676 | this.add(model, _.extend({at: 0}, options)); 677 | return model; 678 | }, 679 | 680 | // Remove a model from the beginning of the collection. 681 | shift: function(options) { 682 | var model = this.at(0); 683 | this.remove(model, options); 684 | return model; 685 | }, 686 | 687 | // Get a model from the set by id. 688 | get: function(id) { 689 | if (id == null) return void 0; 690 | return this._byId[id.id != null ? id.id : id]; 691 | }, 692 | 693 | // Get a model from the set by client id. 694 | getByCid: function(cid) { 695 | return cid && this._byCid[cid.cid || cid]; 696 | }, 697 | 698 | // Get the model at the given index. 699 | at: function(index) { 700 | return this.models[index]; 701 | }, 702 | 703 | // Return models with matching attributes. Useful for simple cases of `filter`. 704 | where: function(attrs) { 705 | if (_.isEmpty(attrs)) return []; 706 | return this.filter(function(model) { 707 | for (var key in attrs) { 708 | if (attrs[key] !== model.get(key)) return false; 709 | } 710 | return true; 711 | }); 712 | }, 713 | 714 | // Force the collection to re-sort itself. You don't need to call this under 715 | // normal circumstances, as the set will maintain sort order as each item 716 | // is added. 717 | sort: function(options) { 718 | options || (options = {}); 719 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 720 | var boundComparator = _.bind(this.comparator, this); 721 | if (this.comparator.length == 1) { 722 | this.models = this.sortBy(boundComparator); 723 | } else { 724 | this.models.sort(boundComparator); 725 | } 726 | if (!options.silent) this.trigger('reset', this, options); 727 | return this; 728 | }, 729 | 730 | // Pluck an attribute from each model in the collection. 731 | pluck: function(attr) { 732 | return _.map(this.models, function(model){ return model.get(attr); }); 733 | }, 734 | 735 | // When you have more items than you want to add or remove individually, 736 | // you can reset the entire set with a new list of models, without firing 737 | // any `add` or `remove` events. Fires `reset` when finished. 738 | reset: function(models, options) { 739 | models || (models = []); 740 | options || (options = {}); 741 | for (var i = 0, l = this.models.length; i < l; i++) { 742 | this._removeReference(this.models[i]); 743 | } 744 | this._reset(); 745 | this.add(models, _.extend({silent: true}, options)); 746 | if (!options.silent) this.trigger('reset', this, options); 747 | return this; 748 | }, 749 | 750 | // Fetch the default set of models for this collection, resetting the 751 | // collection when they arrive. If `add: true` is passed, appends the 752 | // models to the collection instead of resetting. 753 | fetch: function(options) { 754 | options = options ? _.clone(options) : {}; 755 | if (options.parse === undefined) options.parse = true; 756 | var collection = this; 757 | var success = options.success; 758 | options.success = function(resp, status, xhr) { 759 | collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); 760 | if (success) success(collection, resp); 761 | }; 762 | options.error = Backbone.wrapError(options.error, collection, options); 763 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 764 | }, 765 | 766 | // Create a new instance of a model in this collection. Add the model to the 767 | // collection immediately, unless `wait: true` is passed, in which case we 768 | // wait for the server to agree. 769 | create: function(model, options) { 770 | var coll = this; 771 | options = options ? _.clone(options) : {}; 772 | model = this._prepareModel(model, options); 773 | if (!model) return false; 774 | if (!options.wait) coll.add(model, options); 775 | var success = options.success; 776 | options.success = function(nextModel, resp, xhr) { 777 | if (options.wait) coll.add(nextModel, options); 778 | if (success) { 779 | success(nextModel, resp); 780 | } else { 781 | nextModel.trigger('sync', model, resp, options); 782 | } 783 | }; 784 | model.save(null, options); 785 | return model; 786 | }, 787 | 788 | // **parse** converts a response into a list of models to be added to the 789 | // collection. The default implementation is just to pass it through. 790 | parse: function(resp, xhr) { 791 | return resp; 792 | }, 793 | 794 | // Proxy to _'s chain. Can't be proxied the same way the rest of the 795 | // underscore methods are proxied because it relies on the underscore 796 | // constructor. 797 | chain: function () { 798 | return _(this.models).chain(); 799 | }, 800 | 801 | // Reset all internal state. Called when the collection is reset. 802 | _reset: function(options) { 803 | this.length = 0; 804 | this.models = []; 805 | this._byId = {}; 806 | this._byCid = {}; 807 | }, 808 | 809 | // Prepare a model or hash of attributes to be added to this collection. 810 | _prepareModel: function(model, options) { 811 | options || (options = {}); 812 | if (!(model instanceof Model)) { 813 | var attrs = model; 814 | options.collection = this; 815 | model = new this.model(attrs, options); 816 | if (!model._validate(model.attributes, options)) model = false; 817 | } else if (!model.collection) { 818 | model.collection = this; 819 | } 820 | return model; 821 | }, 822 | 823 | // Internal method to remove a model's ties to a collection. 824 | _removeReference: function(model) { 825 | if (this == model.collection) { 826 | delete model.collection; 827 | } 828 | model.off('all', this._onModelEvent, this); 829 | }, 830 | 831 | // Internal method called every time a model in the set fires an event. 832 | // Sets need to update their indexes when models change ids. All other 833 | // events simply proxy through. "add" and "remove" events that originate 834 | // in other collections are ignored. 835 | _onModelEvent: function(event, model, collection, options) { 836 | if ((event == 'add' || event == 'remove') && collection != this) return; 837 | if (event == 'destroy') { 838 | this.remove(model, options); 839 | } 840 | if (model && event === 'change:' + model.idAttribute) { 841 | delete this._byId[model.previous(model.idAttribute)]; 842 | this._byId[model.id] = model; 843 | } 844 | this.trigger.apply(this, arguments); 845 | } 846 | 847 | }); 848 | 849 | // Underscore methods that we want to implement on the Collection. 850 | var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 851 | 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 852 | 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 853 | 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', 854 | 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; 855 | 856 | // Mix in each Underscore method as a proxy to `Collection#models`. 857 | _.each(methods, function(method) { 858 | Collection.prototype[method] = function() { 859 | return _[method].apply(_, [this.models].concat(_.toArray(arguments))); 860 | }; 861 | }); 862 | 863 | // Backbone.Router 864 | // ------------------- 865 | 866 | // Routers map faux-URLs to actions, and fire events when routes are 867 | // matched. Creating a new one sets its `routes` hash, if not set statically. 868 | var Router = Backbone.Router = function(options) { 869 | options || (options = {}); 870 | if (options.routes) this.routes = options.routes; 871 | this._bindRoutes(); 872 | this.initialize.apply(this, arguments); 873 | }; 874 | 875 | // Cached regular expressions for matching named param parts and splatted 876 | // parts of route strings. 877 | var namedParam = /:\w+/g; 878 | var splatParam = /\*\w+/g; 879 | var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; 880 | 881 | // Set up all inheritable **Backbone.Router** properties and methods. 882 | _.extend(Router.prototype, Events, { 883 | 884 | // Initialize is an empty function by default. Override it with your own 885 | // initialization logic. 886 | initialize: function(){}, 887 | 888 | // Manually bind a single named route to a callback. For example: 889 | // 890 | // this.route('search/:query/p:num', 'search', function(query, num) { 891 | // ... 892 | // }); 893 | // 894 | route: function(route, name, callback) { 895 | Backbone.history || (Backbone.history = new History); 896 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 897 | if (!callback) callback = this[name]; 898 | Backbone.history.route(route, _.bind(function(fragment) { 899 | var args = this._extractParameters(route, fragment); 900 | callback && callback.apply(this, args); 901 | this.trigger.apply(this, ['route:' + name].concat(args)); 902 | Backbone.history.trigger('route', this, name, args); 903 | }, this)); 904 | return this; 905 | }, 906 | 907 | // Simple proxy to `Backbone.history` to save a fragment into the history. 908 | navigate: function(fragment, options) { 909 | Backbone.history.navigate(fragment, options); 910 | }, 911 | 912 | // Bind all defined routes to `Backbone.history`. We have to reverse the 913 | // order of the routes here to support behavior where the most general 914 | // routes can be defined at the bottom of the route map. 915 | _bindRoutes: function() { 916 | if (!this.routes) return; 917 | var routes = []; 918 | for (var route in this.routes) { 919 | routes.unshift([route, this.routes[route]]); 920 | } 921 | for (var i = 0, l = routes.length; i < l; i++) { 922 | this.route(routes[i][0], routes[i][1], this[routes[i][1]]); 923 | } 924 | }, 925 | 926 | // Convert a route string into a regular expression, suitable for matching 927 | // against the current location hash. 928 | _routeToRegExp: function(route) { 929 | route = route.replace(escapeRegExp, '\\$&') 930 | .replace(namedParam, '([^\/]+)') 931 | .replace(splatParam, '(.*?)'); 932 | return new RegExp('^' + route + '$'); 933 | }, 934 | 935 | // Given a route, and a URL fragment that it matches, return the array of 936 | // extracted parameters. 937 | _extractParameters: function(route, fragment) { 938 | return route.exec(fragment).slice(1); 939 | } 940 | 941 | }); 942 | 943 | // Backbone.History 944 | // ---------------- 945 | 946 | // Handles cross-browser history management, based on URL fragments. If the 947 | // browser does not support `onhashchange`, falls back to polling. 948 | var History = Backbone.History = function() { 949 | this.handlers = []; 950 | _.bindAll(this, 'checkUrl'); 951 | }; 952 | 953 | // Cached regex for cleaning leading hashes and slashes . 954 | var routeStripper = /^[#\/]/; 955 | 956 | // Cached regex for detecting MSIE. 957 | var isExplorer = /msie [\w.]+/; 958 | 959 | // Has the history handling already been started? 960 | History.started = false; 961 | 962 | // Set up all inheritable **Backbone.History** properties and methods. 963 | _.extend(History.prototype, Events, { 964 | 965 | // The default interval to poll for hash changes, if necessary, is 966 | // twenty times a second. 967 | interval: 50, 968 | 969 | // Gets the true hash value. Cannot use location.hash directly due to bug 970 | // in Firefox where location.hash will always be decoded. 971 | getHash: function(windowOverride) { 972 | var loc = windowOverride ? windowOverride.location : window.location; 973 | var match = loc.href.match(/#(.*)$/); 974 | return match ? match[1] : ''; 975 | }, 976 | 977 | // Get the cross-browser normalized URL fragment, either from the URL, 978 | // the hash, or the override. 979 | getFragment: function(fragment, forcePushState) { 980 | if (fragment == null) { 981 | if (this._hasPushState || forcePushState) { 982 | fragment = window.location.pathname; 983 | var search = window.location.search; 984 | if (search) fragment += search; 985 | } else { 986 | fragment = this.getHash(); 987 | } 988 | } 989 | if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); 990 | return fragment.replace(routeStripper, ''); 991 | }, 992 | 993 | // Start the hash change handling, returning `true` if the current URL matches 994 | // an existing route, and `false` otherwise. 995 | start: function(options) { 996 | if (History.started) throw new Error("Backbone.history has already been started"); 997 | History.started = true; 998 | 999 | // Figure out the initial configuration. Do we need an iframe? 1000 | // Is pushState desired ... is it available? 1001 | this.options = _.extend({}, {root: '/'}, this.options, options); 1002 | this._wantsHashChange = this.options.hashChange !== false; 1003 | this._wantsPushState = !!this.options.pushState; 1004 | this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); 1005 | var fragment = this.getFragment(); 1006 | var docMode = document.documentMode; 1007 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1008 | 1009 | if (oldIE) { 1010 | this.iframe = $('