tableling-rails 0.0.20 → 0.0.21

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,15 @@
1
+ ---
2
+ !binary "U0hBMQ==":
3
+ metadata.gz: !binary |-
4
+ NmViN2FiZGUxZDhmZTQ5NDYzYjM5NzViMTUyYWFiNmFhZjZhZGEzZA==
5
+ data.tar.gz: !binary |-
6
+ NjNjNWFlN2NiOTJiNGQzMjBjMWY3NDU4NzQ5NzQwNWM1NjlmMzdhMg==
7
+ SHA512:
8
+ metadata.gz: !binary |-
9
+ MjQzNWI5MTliMmI1NDU4MGYxMGUwNzVmYzJhOWIxM2I2YmJkNDZiNzMxZjUz
10
+ NmU1YTBiMGUzNDE3YWFiNDc4ZmQ1OWMyODRmNjYwZGFiMTYxZjg4ZGY0MDMy
11
+ MzJmMDU0OTFkNTA1Nzk1NjYwYWM3ZThmNGY2NjlhNWVlMWQzY2M=
12
+ data.tar.gz: !binary |-
13
+ Y2JiYTkyZWJhY2FjYWQ5MjJiYTljZTYxMTQyMDIxMzBkYmIyNTMxNDgwN2Fl
14
+ YTY4ZDdlZDk0MzBiNWM0NTgyNDNmODdkZDhjN2FhNzQyMzBmYjExMDUwYzE0
15
+ ODQxMDYwNDUxMDU3ODZmMjZkZTMyZTYxNjcyNDk3NjgxZGRiMWQ=
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.21
@@ -1,3 +1,3 @@
1
1
  module Tableling
2
- VERSION = "0.0.20"
2
+ VERSION = "0.0.21"
3
3
  end
@@ -100,7 +100,7 @@ module Tableling
100
100
 
101
101
  def serialize_response query, response_options = {}
102
102
 
103
- res = response_options.merge data: query.all
103
+ res = response_options.merge data: query.to_a
104
104
 
105
105
  if @serialize_response_block
106
106
  @serialize_response_block.call res
@@ -43,12 +43,6 @@ module Dummy
43
43
  # like if you have constraints or database-specific column types
44
44
  # config.active_record.schema_format = :sql
45
45
 
46
- # Enforce whitelist mode for mass assignment.
47
- # This will create an empty whitelist of attributes available for mass-assignment for all models
48
- # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
49
- # parameters by using an attr_accessible or attr_protected declaration.
50
- config.active_record.whitelist_attributes = true
51
-
52
46
  # Enable the asset pipeline
53
47
  config.assets.enabled = true
54
48
 
@@ -6,6 +6,9 @@ Dummy::Application.configure do
6
6
  # since you don't have to restart the web server when you make code changes.
7
7
  config.cache_classes = false
8
8
 
9
+ # Do not eager load code on boot.
10
+ config.eager_load = false
11
+
9
12
  # Log error messages when you accidentally call methods on nil.
10
13
  config.whiny_nils = true
11
14
 
@@ -22,9 +25,6 @@ Dummy::Application.configure do
22
25
  # Only use best-standards-support built into browsers
23
26
  config.action_dispatch.best_standards_support = :builtin
24
27
 
25
- # Raise exception on mass assignment protection for Active Record models
26
- config.active_record.mass_assignment_sanitizer = :strict
27
-
28
28
  # Log the query plan for queries taking more than this (works
29
29
  # with SQLite, MySQL, and PostgreSQL)
30
30
  config.active_record.auto_explain_threshold_in_seconds = 0.5
@@ -4,6 +4,12 @@ Dummy::Application.configure do
4
4
  # Code is not reloaded between requests
5
5
  config.cache_classes = true
6
6
 
7
+ # Eager load code on boot. This eager loads most of Rails and
8
+ # your application in memory, allowing both thread web servers
9
+ # and those relying on copy on write to perform better.
10
+ # Rake tasks automatically ignore this option for performance.
11
+ config.eager_load = true
12
+
7
13
  # Full error reports are disabled and caching is turned on
8
14
  config.consider_all_requests_local = false
9
15
  config.action_controller.perform_caching = true
@@ -7,13 +7,13 @@ Dummy::Application.configure do
7
7
  # and recreated between test runs. Don't rely on the data there!
8
8
  config.cache_classes = true
9
9
 
10
+ # Do not eager load code on boot.
11
+ config.eager_load = false
12
+
10
13
  # Configure static asset server for tests with Cache-Control for performance
11
14
  config.serve_static_assets = true
12
15
  config.static_cache_control = "public, max-age=3600"
13
16
 
14
- # Log error messages when you accidentally call methods on nil
15
- config.whiny_nils = true
16
-
17
17
  # Show full error reports and disable caching
18
18
  config.consider_all_requests_local = true
19
19
  config.action_controller.perform_caching = false
@@ -29,9 +29,6 @@ Dummy::Application.configure do
29
29
  # ActionMailer::Base.deliveries array.
30
30
  config.action_mailer.delivery_method = :test
31
31
 
32
- # Raise exception on mass assignment protection for Active Record models
33
- config.active_record.mass_assignment_sanitizer = :strict
34
-
35
32
  # Print deprecation notices to the stderr
36
33
  config.active_support.deprecation = :stderr
37
34
  end
Binary file
@@ -57,3 +57,17 @@ Connecting to database specified by database.yml
57
57
   (0.8ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
58
58
   (0.8ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
59
59
   (0.1ms) SELECT version FROM "schema_migrations"
60
+ Connecting to database specified by database.yml
61
+  (4.4ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
62
+  (0.2ms) select sqlite_version(*)
63
+  (1.2ms) DROP TABLE "books"
64
+  (0.8ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
65
+  (0.7ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
66
+  (0.1ms) SELECT version FROM "schema_migrations"
67
+ Connecting to database specified by database.yml
68
+  (1.6ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
69
+  (0.2ms) select sqlite_version(*)
70
+  (0.9ms) DROP TABLE "books"
71
+  (0.7ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
72
+  (0.7ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
73
+  (0.1ms) SELECT version FROM "schema_migrations"
@@ -28,3 +28,65 @@ Migrating to CreateBooks (20121008115302)
28
28
   (0.0ms) rollback transaction
29
29
   (0.0ms) begin transaction
30
30
   (0.0ms) rollback transaction
31
+ Connecting to database specified by database.yml
32
+  (1.3ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
33
+ Migrating to CreateBooks (20121008115302)
34
+  (0.1ms) begin transaction
35
+  (0.0ms) rollback transaction
36
+  (0.0ms) begin transaction
37
+  (0.1ms) rollback transaction
38
+ Connecting to database specified by database.yml
39
+  (1.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
40
+ Migrating to CreateBooks (20121008115302)
41
+  (0.1ms) begin transaction
42
+  (0.0ms) rollback transaction
43
+  (0.1ms) begin transaction
44
+  (0.1ms) rollback transaction
45
+  (1.1ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 
46
+  (0.8ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
47
+  (13.7ms) CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) 
48
+  (0.9ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
49
+  (0.1ms) SELECT version FROM "schema_migrations"
50
+  (5.6ms) INSERT INTO "schema_migrations" (version) VALUES ('20121008115302')
51
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
52
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
53
+  (0.1ms) begin transaction
54
+  (0.1ms) rollback transaction
55
+  (0.1ms) begin transaction
56
+  (0.1ms) rollback transaction
57
+  (1.0ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 
58
+  (0.8ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
59
+  (10.8ms) CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) 
60
+  (0.9ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
61
+  (0.1ms) SELECT version FROM "schema_migrations"
62
+  (5.5ms) INSERT INTO "schema_migrations" (version) VALUES ('20121008115302')
63
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
64
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
65
+  (0.1ms) begin transaction
66
+  (0.1ms) rollback transaction
67
+  (0.1ms) begin transaction
68
+  (0.1ms) rollback transaction
69
+  (5.6ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 
70
+  (0.9ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
71
+  (0.9ms) CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) 
72
+  (0.7ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
73
+  (0.1ms) SELECT version FROM "schema_migrations"
74
+  (0.8ms) INSERT INTO "schema_migrations" (version) VALUES ('20121008115302')
75
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
76
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
77
+  (0.1ms) begin transaction
78
+  (0.1ms) rollback transaction
79
+  (0.1ms) begin transaction
80
+  (0.1ms) rollback transaction
81
+  (1.4ms) CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255) NOT NULL, "author" varchar(255) NOT NULL, "year" integer NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) 
82
+  (0.7ms) CREATE UNIQUE INDEX "index_books_on_title" ON "books" ("title")
83
+  (0.8ms) CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) 
84
+  (0.9ms) CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
85
+  (0.1ms) SELECT version FROM "schema_migrations"
86
+  (0.6ms) INSERT INTO "schema_migrations" (version) VALUES ('20121008115302')
87
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
88
+ ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
89
+  (0.1ms) begin transaction
90
+  (0.1ms) rollback transaction
91
+  (0.0ms) begin transaction
92
+  (0.0ms) rollback transaction
metadata CHANGED
@@ -1,32 +1,29 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tableling-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.20
5
- prerelease:
4
+ version: 0.0.21
6
5
  platform: ruby
7
6
  authors:
8
7
  - Simon Oulevay
9
8
  autorequire:
10
9
  bindir: bin
11
10
  cert_chain: []
12
- date: 2013-07-22 00:00:00.000000000 Z
11
+ date: 2013-12-30 00:00:00.000000000 Z
13
12
  dependencies:
14
13
  - !ruby/object:Gem::Dependency
15
14
  name: rails
16
15
  requirement: !ruby/object:Gem::Requirement
17
- none: false
18
16
  requirements:
19
17
  - - ~>
20
18
  - !ruby/object:Gem::Version
21
- version: '3.2'
19
+ version: '4.0'
22
20
  type: :runtime
23
21
  prerelease: false
24
22
  version_requirements: !ruby/object:Gem::Requirement
25
- none: false
26
23
  requirements:
27
24
  - - ~>
28
25
  - !ruby/object:Gem::Version
29
- version: '3.2'
26
+ version: '4.0'
30
27
  description: Javascript assets for the latest Tableling release and active record
31
28
  extensions to easily generate table data.
32
29
  email:
@@ -46,12 +43,9 @@ files:
46
43
  - lib/tableling-rails/version.rb
47
44
  - lib/tableling-rails/view.rb
48
45
  - lib/tableling-rails.rb
49
- - vendor/assets/javascripts/tableling.backbone.js
50
- - vendor/assets/javascripts/tableling.js
51
- - vendor/assets/javascripts/tableling.world.js
52
46
  - LICENSE.txt
53
- - Rakefile
54
47
  - README.md
48
+ - VERSION
55
49
  - spec/dummy/app/assets/javascripts/application.js
56
50
  - spec/dummy/app/assets/javascripts/books.js
57
51
  - spec/dummy/app/assets/javascripts/bootstrap.js
@@ -114,33 +108,26 @@ files:
114
108
  homepage: https://github.com/AlphaHydrae/tableling-rails
115
109
  licenses:
116
110
  - MIT
111
+ metadata: {}
117
112
  post_install_message:
118
113
  rdoc_options: []
119
114
  require_paths:
120
115
  - lib
121
116
  required_ruby_version: !ruby/object:Gem::Requirement
122
- none: false
123
117
  requirements:
124
118
  - - ! '>='
125
119
  - !ruby/object:Gem::Version
126
120
  version: '0'
127
- segments:
128
- - 0
129
- hash: 1244003446696768491
130
121
  required_rubygems_version: !ruby/object:Gem::Requirement
131
- none: false
132
122
  requirements:
133
123
  - - ! '>='
134
124
  - !ruby/object:Gem::Version
135
125
  version: '0'
136
- segments:
137
- - 0
138
- hash: 1244003446696768491
139
126
  requirements: []
140
127
  rubyforge_project:
141
- rubygems_version: 1.8.25
128
+ rubygems_version: 2.1.10
142
129
  signing_key:
143
- specification_version: 3
130
+ specification_version: 4
144
131
  summary: Tableling gem for Ruby on Rails.
145
132
  test_files:
146
133
  - spec/dummy/app/assets/javascripts/application.js
data/Rakefile DELETED
@@ -1,19 +0,0 @@
1
- #!/usr/bin/env rake
2
- begin
3
- require 'bundler/setup'
4
- rescue LoadError
5
- puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
6
- end
7
-
8
- Bundler::GemHelper.install_tasks
9
-
10
- require File.expand_path('../spec/dummy/config/application', __FILE__)
11
- require 'rspec-rails'
12
- Dummy::Application.load_tasks
13
-
14
- require 'rake-version'
15
- RakeVersion::Tasks.new do |v|
16
- v.copy 'lib/tableling-rails/version.rb'
17
- end
18
-
19
- task :default => :spec
@@ -1,4586 +0,0 @@
1
- // Backbone.js 1.0.0
2
-
3
- // (c) 2010-2013 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, `exports`
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 local references to array methods we'll want to use later.
22
- var array = [];
23
- var push = array.push;
24
- var slice = array.slice;
25
- var splice = array.splice;
26
-
27
- // The top-level namespace. All public Backbone classes and modules will
28
- // be attached to this. Exported for both the browser and the server.
29
- var Backbone;
30
- if (typeof exports !== 'undefined') {
31
- Backbone = exports;
32
- } else {
33
- Backbone = root.Backbone = {};
34
- }
35
-
36
- // Current version of the library. Keep in sync with `package.json`.
37
- Backbone.VERSION = '1.0.0';
38
-
39
- // Require Underscore, if we're on the server, and it's not already present.
40
- var _ = root._;
41
- if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
42
-
43
- // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
44
- // the `$` variable.
45
- Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
46
-
47
- // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
48
- // to its previous owner. Returns a reference to this Backbone object.
49
- Backbone.noConflict = function() {
50
- root.Backbone = previousBackbone;
51
- return this;
52
- };
53
-
54
- // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
55
- // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
56
- // set a `X-Http-Method-Override` header.
57
- Backbone.emulateHTTP = false;
58
-
59
- // Turn on `emulateJSON` to support legacy servers that can't deal with direct
60
- // `application/json` requests ... will encode the body as
61
- // `application/x-www-form-urlencoded` instead and will send the model in a
62
- // form param named `model`.
63
- Backbone.emulateJSON = false;
64
-
65
- // Backbone.Events
66
- // ---------------
67
-
68
- // A module that can be mixed in to *any object* in order to provide it with
69
- // custom events. You may bind with `on` or remove with `off` callback
70
- // functions to an event; `trigger`-ing an event fires all callbacks in
71
- // succession.
72
- //
73
- // var object = {};
74
- // _.extend(object, Backbone.Events);
75
- // object.on('expand', function(){ alert('expanded'); });
76
- // object.trigger('expand');
77
- //
78
- var Events = Backbone.Events = {
79
-
80
- // Bind an event to a `callback` function. Passing `"all"` will bind
81
- // the callback to all events fired.
82
- on: function(name, callback, context) {
83
- if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
84
- this._events || (this._events = {});
85
- var events = this._events[name] || (this._events[name] = []);
86
- events.push({callback: callback, context: context, ctx: context || this});
87
- return this;
88
- },
89
-
90
- // Bind an event to only be triggered a single time. After the first time
91
- // the callback is invoked, it will be removed.
92
- once: function(name, callback, context) {
93
- if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
94
- var self = this;
95
- var once = _.once(function() {
96
- self.off(name, once);
97
- callback.apply(this, arguments);
98
- });
99
- once._callback = callback;
100
- return this.on(name, once, context);
101
- },
102
-
103
- // Remove one or many callbacks. If `context` is null, removes all
104
- // callbacks with that function. If `callback` is null, removes all
105
- // callbacks for the event. If `name` is null, removes all bound
106
- // callbacks for all events.
107
- off: function(name, callback, context) {
108
- var retain, ev, events, names, i, l, j, k;
109
- if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
110
- if (!name && !callback && !context) {
111
- this._events = {};
112
- return this;
113
- }
114
-
115
- names = name ? [name] : _.keys(this._events);
116
- for (i = 0, l = names.length; i < l; i++) {
117
- name = names[i];
118
- if (events = this._events[name]) {
119
- this._events[name] = retain = [];
120
- if (callback || context) {
121
- for (j = 0, k = events.length; j < k; j++) {
122
- ev = events[j];
123
- if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
124
- (context && context !== ev.context)) {
125
- retain.push(ev);
126
- }
127
- }
128
- }
129
- if (!retain.length) delete this._events[name];
130
- }
131
- }
132
-
133
- return this;
134
- },
135
-
136
- // Trigger one or many events, firing all bound callbacks. Callbacks are
137
- // passed the same arguments as `trigger` is, apart from the event name
138
- // (unless you're listening on `"all"`, which will cause your callback to
139
- // receive the true name of the event as the first argument).
140
- trigger: function(name) {
141
- if (!this._events) return this;
142
- var args = slice.call(arguments, 1);
143
- if (!eventsApi(this, 'trigger', name, args)) return this;
144
- var events = this._events[name];
145
- var allEvents = this._events.all;
146
- if (events) triggerEvents(events, args);
147
- if (allEvents) triggerEvents(allEvents, arguments);
148
- return this;
149
- },
150
-
151
- // Tell this object to stop listening to either specific events ... or
152
- // to every object it's currently listening to.
153
- stopListening: function(obj, name, callback) {
154
- var listeners = this._listeners;
155
- if (!listeners) return this;
156
- var deleteListener = !name && !callback;
157
- if (typeof name === 'object') callback = this;
158
- if (obj) (listeners = {})[obj._listenerId] = obj;
159
- for (var id in listeners) {
160
- listeners[id].off(name, callback, this);
161
- if (deleteListener) delete this._listeners[id];
162
- }
163
- return this;
164
- }
165
-
166
- };
167
-
168
- // Regular expression used to split event strings.
169
- var eventSplitter = /\s+/;
170
-
171
- // Implement fancy features of the Events API such as multiple event
172
- // names `"change blur"` and jQuery-style event maps `{change: action}`
173
- // in terms of the existing API.
174
- var eventsApi = function(obj, action, name, rest) {
175
- if (!name) return true;
176
-
177
- // Handle event maps.
178
- if (typeof name === 'object') {
179
- for (var key in name) {
180
- obj[action].apply(obj, [key, name[key]].concat(rest));
181
- }
182
- return false;
183
- }
184
-
185
- // Handle space separated event names.
186
- if (eventSplitter.test(name)) {
187
- var names = name.split(eventSplitter);
188
- for (var i = 0, l = names.length; i < l; i++) {
189
- obj[action].apply(obj, [names[i]].concat(rest));
190
- }
191
- return false;
192
- }
193
-
194
- return true;
195
- };
196
-
197
- // A difficult-to-believe, but optimized internal dispatch function for
198
- // triggering events. Tries to keep the usual cases speedy (most internal
199
- // Backbone events have 3 arguments).
200
- var triggerEvents = function(events, args) {
201
- var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
202
- switch (args.length) {
203
- case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
204
- case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
205
- case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
206
- case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
207
- default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
208
- }
209
- };
210
-
211
- var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
212
-
213
- // Inversion-of-control versions of `on` and `once`. Tell *this* object to
214
- // listen to an event in another object ... keeping track of what it's
215
- // listening to.
216
- _.each(listenMethods, function(implementation, method) {
217
- Events[method] = function(obj, name, callback) {
218
- var listeners = this._listeners || (this._listeners = {});
219
- var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
220
- listeners[id] = obj;
221
- if (typeof name === 'object') callback = this;
222
- obj[implementation](name, callback, this);
223
- return this;
224
- };
225
- });
226
-
227
- // Aliases for backwards compatibility.
228
- Events.bind = Events.on;
229
- Events.unbind = Events.off;
230
-
231
- // Allow the `Backbone` object to serve as a global event bus, for folks who
232
- // want global "pubsub" in a convenient place.
233
- _.extend(Backbone, Events);
234
-
235
- // Backbone.Model
236
- // --------------
237
-
238
- // Backbone **Models** are the basic data object in the framework --
239
- // frequently representing a row in a table in a database on your server.
240
- // A discrete chunk of data and a bunch of useful, related methods for
241
- // performing computations and transformations on that data.
242
-
243
- // Create a new model with the specified attributes. A client id (`cid`)
244
- // is automatically generated and assigned for you.
245
- var Model = Backbone.Model = function(attributes, options) {
246
- var defaults;
247
- var attrs = attributes || {};
248
- options || (options = {});
249
- this.cid = _.uniqueId('c');
250
- this.attributes = {};
251
- _.extend(this, _.pick(options, modelOptions));
252
- if (options.parse) attrs = this.parse(attrs, options) || {};
253
- if (defaults = _.result(this, 'defaults')) {
254
- attrs = _.defaults({}, attrs, defaults);
255
- }
256
- this.set(attrs, options);
257
- this.changed = {};
258
- this.initialize.apply(this, arguments);
259
- };
260
-
261
- // A list of options to be attached directly to the model, if provided.
262
- var modelOptions = ['url', 'urlRoot', 'collection'];
263
-
264
- // Attach all inheritable methods to the Model prototype.
265
- _.extend(Model.prototype, Events, {
266
-
267
- // A hash of attributes whose current and previous value differ.
268
- changed: null,
269
-
270
- // The value returned during the last failed validation.
271
- validationError: null,
272
-
273
- // The default name for the JSON `id` attribute is `"id"`. MongoDB and
274
- // CouchDB users may want to set this to `"_id"`.
275
- idAttribute: 'id',
276
-
277
- // Initialize is an empty function by default. Override it with your own
278
- // initialization logic.
279
- initialize: function(){},
280
-
281
- // Return a copy of the model's `attributes` object.
282
- toJSON: function(options) {
283
- return _.clone(this.attributes);
284
- },
285
-
286
- // Proxy `Backbone.sync` by default -- but override this if you need
287
- // custom syncing semantics for *this* particular model.
288
- sync: function() {
289
- return Backbone.sync.apply(this, arguments);
290
- },
291
-
292
- // Get the value of an attribute.
293
- get: function(attr) {
294
- return this.attributes[attr];
295
- },
296
-
297
- // Get the HTML-escaped value of an attribute.
298
- escape: function(attr) {
299
- return _.escape(this.get(attr));
300
- },
301
-
302
- // Returns `true` if the attribute contains a value that is not null
303
- // or undefined.
304
- has: function(attr) {
305
- return this.get(attr) != null;
306
- },
307
-
308
- // Set a hash of model attributes on the object, firing `"change"`. This is
309
- // the core primitive operation of a model, updating the data and notifying
310
- // anyone who needs to know about the change in state. The heart of the beast.
311
- set: function(key, val, options) {
312
- var attr, attrs, unset, changes, silent, changing, prev, current;
313
- if (key == null) return this;
314
-
315
- // Handle both `"key", value` and `{key: value}` -style arguments.
316
- if (typeof key === 'object') {
317
- attrs = key;
318
- options = val;
319
- } else {
320
- (attrs = {})[key] = val;
321
- }
322
-
323
- options || (options = {});
324
-
325
- // Run validation.
326
- if (!this._validate(attrs, options)) return false;
327
-
328
- // Extract attributes and options.
329
- unset = options.unset;
330
- silent = options.silent;
331
- changes = [];
332
- changing = this._changing;
333
- this._changing = true;
334
-
335
- if (!changing) {
336
- this._previousAttributes = _.clone(this.attributes);
337
- this.changed = {};
338
- }
339
- current = this.attributes, prev = this._previousAttributes;
340
-
341
- // Check for changes of `id`.
342
- if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
343
-
344
- // For each `set` attribute, update or delete the current value.
345
- for (attr in attrs) {
346
- val = attrs[attr];
347
- if (!_.isEqual(current[attr], val)) changes.push(attr);
348
- if (!_.isEqual(prev[attr], val)) {
349
- this.changed[attr] = val;
350
- } else {
351
- delete this.changed[attr];
352
- }
353
- unset ? delete current[attr] : current[attr] = val;
354
- }
355
-
356
- // Trigger all relevant attribute changes.
357
- if (!silent) {
358
- if (changes.length) this._pending = true;
359
- for (var i = 0, l = changes.length; i < l; i++) {
360
- this.trigger('change:' + changes[i], this, current[changes[i]], options);
361
- }
362
- }
363
-
364
- // You might be wondering why there's a `while` loop here. Changes can
365
- // be recursively nested within `"change"` events.
366
- if (changing) return this;
367
- if (!silent) {
368
- while (this._pending) {
369
- this._pending = false;
370
- this.trigger('change', this, options);
371
- }
372
- }
373
- this._pending = false;
374
- this._changing = false;
375
- return this;
376
- },
377
-
378
- // Remove an attribute from the model, firing `"change"`. `unset` is a noop
379
- // if the attribute doesn't exist.
380
- unset: function(attr, options) {
381
- return this.set(attr, void 0, _.extend({}, options, {unset: true}));
382
- },
383
-
384
- // Clear all attributes on the model, firing `"change"`.
385
- clear: function(options) {
386
- var attrs = {};
387
- for (var key in this.attributes) attrs[key] = void 0;
388
- return this.set(attrs, _.extend({}, options, {unset: true}));
389
- },
390
-
391
- // Determine if the model has changed since the last `"change"` event.
392
- // If you specify an attribute name, determine if that attribute has changed.
393
- hasChanged: function(attr) {
394
- if (attr == null) return !_.isEmpty(this.changed);
395
- return _.has(this.changed, attr);
396
- },
397
-
398
- // Return an object containing all the attributes that have changed, or
399
- // false if there are no changed attributes. Useful for determining what
400
- // parts of a view need to be updated and/or what attributes need to be
401
- // persisted to the server. Unset attributes will be set to undefined.
402
- // You can also pass an attributes object to diff against the model,
403
- // determining if there *would be* a change.
404
- changedAttributes: function(diff) {
405
- if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
406
- var val, changed = false;
407
- var old = this._changing ? this._previousAttributes : this.attributes;
408
- for (var attr in diff) {
409
- if (_.isEqual(old[attr], (val = diff[attr]))) continue;
410
- (changed || (changed = {}))[attr] = val;
411
- }
412
- return changed;
413
- },
414
-
415
- // Get the previous value of an attribute, recorded at the time the last
416
- // `"change"` event was fired.
417
- previous: function(attr) {
418
- if (attr == null || !this._previousAttributes) return null;
419
- return this._previousAttributes[attr];
420
- },
421
-
422
- // Get all of the attributes of the model at the time of the previous
423
- // `"change"` event.
424
- previousAttributes: function() {
425
- return _.clone(this._previousAttributes);
426
- },
427
-
428
- // Fetch the model from the server. If the server's representation of the
429
- // model differs from its current attributes, they will be overridden,
430
- // triggering a `"change"` event.
431
- fetch: function(options) {
432
- options = options ? _.clone(options) : {};
433
- if (options.parse === void 0) options.parse = true;
434
- var model = this;
435
- var success = options.success;
436
- options.success = function(resp) {
437
- if (!model.set(model.parse(resp, options), options)) return false;
438
- if (success) success(model, resp, options);
439
- model.trigger('sync', model, resp, options);
440
- };
441
- wrapError(this, options);
442
- return this.sync('read', this, options);
443
- },
444
-
445
- // Set a hash of model attributes, and sync the model to the server.
446
- // If the server returns an attributes hash that differs, the model's
447
- // state will be `set` again.
448
- save: function(key, val, options) {
449
- var attrs, method, xhr, attributes = this.attributes;
450
-
451
- // Handle both `"key", value` and `{key: value}` -style arguments.
452
- if (key == null || typeof key === 'object') {
453
- attrs = key;
454
- options = val;
455
- } else {
456
- (attrs = {})[key] = val;
457
- }
458
-
459
- // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
460
- if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
461
-
462
- options = _.extend({validate: true}, options);
463
-
464
- // Do not persist invalid models.
465
- if (!this._validate(attrs, options)) return false;
466
-
467
- // Set temporary attributes if `{wait: true}`.
468
- if (attrs && options.wait) {
469
- this.attributes = _.extend({}, attributes, attrs);
470
- }
471
-
472
- // After a successful server-side save, the client is (optionally)
473
- // updated with the server-side state.
474
- if (options.parse === void 0) options.parse = true;
475
- var model = this;
476
- var success = options.success;
477
- options.success = function(resp) {
478
- // Ensure attributes are restored during synchronous saves.
479
- model.attributes = attributes;
480
- var serverAttrs = model.parse(resp, options);
481
- if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
482
- if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
483
- return false;
484
- }
485
- if (success) success(model, resp, options);
486
- model.trigger('sync', model, resp, options);
487
- };
488
- wrapError(this, options);
489
-
490
- method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
491
- if (method === 'patch') options.attrs = attrs;
492
- xhr = this.sync(method, this, options);
493
-
494
- // Restore attributes.
495
- if (attrs && options.wait) this.attributes = attributes;
496
-
497
- return xhr;
498
- },
499
-
500
- // Destroy this model on the server if it was already persisted.
501
- // Optimistically removes the model from its collection, if it has one.
502
- // If `wait: true` is passed, waits for the server to respond before removal.
503
- destroy: function(options) {
504
- options = options ? _.clone(options) : {};
505
- var model = this;
506
- var success = options.success;
507
-
508
- var destroy = function() {
509
- model.trigger('destroy', model, model.collection, options);
510
- };
511
-
512
- options.success = function(resp) {
513
- if (options.wait || model.isNew()) destroy();
514
- if (success) success(model, resp, options);
515
- if (!model.isNew()) model.trigger('sync', model, resp, options);
516
- };
517
-
518
- if (this.isNew()) {
519
- options.success();
520
- return false;
521
- }
522
- wrapError(this, options);
523
-
524
- var xhr = this.sync('delete', this, options);
525
- if (!options.wait) destroy();
526
- return xhr;
527
- },
528
-
529
- // Default URL for the model's representation on the server -- if you're
530
- // using Backbone's restful methods, override this to change the endpoint
531
- // that will be called.
532
- url: function() {
533
- var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
534
- if (this.isNew()) return base;
535
- return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
536
- },
537
-
538
- // **parse** converts a response into the hash of attributes to be `set` on
539
- // the model. The default implementation is just to pass the response along.
540
- parse: function(resp, options) {
541
- return resp;
542
- },
543
-
544
- // Create a new model with identical attributes to this one.
545
- clone: function() {
546
- return new this.constructor(this.attributes);
547
- },
548
-
549
- // A model is new if it has never been saved to the server, and lacks an id.
550
- isNew: function() {
551
- return this.id == null;
552
- },
553
-
554
- // Check if the model is currently in a valid state.
555
- isValid: function(options) {
556
- return this._validate({}, _.extend(options || {}, { validate: true }));
557
- },
558
-
559
- // Run validation against the next complete set of model attributes,
560
- // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
561
- _validate: function(attrs, options) {
562
- if (!options.validate || !this.validate) return true;
563
- attrs = _.extend({}, this.attributes, attrs);
564
- var error = this.validationError = this.validate(attrs, options) || null;
565
- if (!error) return true;
566
- this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
567
- return false;
568
- }
569
-
570
- });
571
-
572
- // Underscore methods that we want to implement on the Model.
573
- var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
574
-
575
- // Mix in each Underscore method as a proxy to `Model#attributes`.
576
- _.each(modelMethods, function(method) {
577
- Model.prototype[method] = function() {
578
- var args = slice.call(arguments);
579
- args.unshift(this.attributes);
580
- return _[method].apply(_, args);
581
- };
582
- });
583
-
584
- // Backbone.Collection
585
- // -------------------
586
-
587
- // If models tend to represent a single row of data, a Backbone Collection is
588
- // more analagous to a table full of data ... or a small slice or page of that
589
- // table, or a collection of rows that belong together for a particular reason
590
- // -- all of the messages in this particular folder, all of the documents
591
- // belonging to this particular author, and so on. Collections maintain
592
- // indexes of their models, both in order, and for lookup by `id`.
593
-
594
- // Create a new **Collection**, perhaps to contain a specific type of `model`.
595
- // If a `comparator` is specified, the Collection will maintain
596
- // its models in sort order, as they're added and removed.
597
- var Collection = Backbone.Collection = function(models, options) {
598
- options || (options = {});
599
- if (options.url) this.url = options.url;
600
- if (options.model) this.model = options.model;
601
- if (options.comparator !== void 0) this.comparator = options.comparator;
602
- this._reset();
603
- this.initialize.apply(this, arguments);
604
- if (models) this.reset(models, _.extend({silent: true}, options));
605
- };
606
-
607
- // Default options for `Collection#set`.
608
- var setOptions = {add: true, remove: true, merge: true};
609
- var addOptions = {add: true, merge: false, remove: false};
610
-
611
- // Define the Collection's inheritable methods.
612
- _.extend(Collection.prototype, Events, {
613
-
614
- // The default model for a collection is just a **Backbone.Model**.
615
- // This should be overridden in most cases.
616
- model: Model,
617
-
618
- // Initialize is an empty function by default. Override it with your own
619
- // initialization logic.
620
- initialize: function(){},
621
-
622
- // The JSON representation of a Collection is an array of the
623
- // models' attributes.
624
- toJSON: function(options) {
625
- return this.map(function(model){ return model.toJSON(options); });
626
- },
627
-
628
- // Proxy `Backbone.sync` by default.
629
- sync: function() {
630
- return Backbone.sync.apply(this, arguments);
631
- },
632
-
633
- // Add a model, or list of models to the set.
634
- add: function(models, options) {
635
- return this.set(models, _.defaults(options || {}, addOptions));
636
- },
637
-
638
- // Remove a model, or a list of models from the set.
639
- remove: function(models, options) {
640
- models = _.isArray(models) ? models.slice() : [models];
641
- options || (options = {});
642
- var i, l, index, model;
643
- for (i = 0, l = models.length; i < l; i++) {
644
- model = this.get(models[i]);
645
- if (!model) continue;
646
- delete this._byId[model.id];
647
- delete this._byId[model.cid];
648
- index = this.indexOf(model);
649
- this.models.splice(index, 1);
650
- this.length--;
651
- if (!options.silent) {
652
- options.index = index;
653
- model.trigger('remove', model, this, options);
654
- }
655
- this._removeReference(model);
656
- }
657
- return this;
658
- },
659
-
660
- // Update a collection by `set`-ing a new list of models, adding new ones,
661
- // removing models that are no longer present, and merging models that
662
- // already exist in the collection, as necessary. Similar to **Model#set**,
663
- // the core operation for updating the data contained by the collection.
664
- set: function(models, options) {
665
- options = _.defaults(options || {}, setOptions);
666
- if (options.parse) models = this.parse(models, options);
667
- if (!_.isArray(models)) models = models ? [models] : [];
668
- var i, l, model, attrs, existing, sort;
669
- var at = options.at;
670
- var sortable = this.comparator && (at == null) && options.sort !== false;
671
- var sortAttr = _.isString(this.comparator) ? this.comparator : null;
672
- var toAdd = [], toRemove = [], modelMap = {};
673
-
674
- // Turn bare objects into model references, and prevent invalid models
675
- // from being added.
676
- for (i = 0, l = models.length; i < l; i++) {
677
- if (!(model = this._prepareModel(models[i], options))) continue;
678
-
679
- // If a duplicate is found, prevent it from being added and
680
- // optionally merge it into the existing model.
681
- if (existing = this.get(model)) {
682
- if (options.remove) modelMap[existing.cid] = true;
683
- if (options.merge) {
684
- existing.set(model.attributes, options);
685
- if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
686
- }
687
-
688
- // This is a new model, push it to the `toAdd` list.
689
- } else if (options.add) {
690
- toAdd.push(model);
691
-
692
- // Listen to added models' events, and index models for lookup by
693
- // `id` and by `cid`.
694
- model.on('all', this._onModelEvent, this);
695
- this._byId[model.cid] = model;
696
- if (model.id != null) this._byId[model.id] = model;
697
- }
698
- }
699
-
700
- // Remove nonexistent models if appropriate.
701
- if (options.remove) {
702
- for (i = 0, l = this.length; i < l; ++i) {
703
- if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
704
- }
705
- if (toRemove.length) this.remove(toRemove, options);
706
- }
707
-
708
- // See if sorting is needed, update `length` and splice in new models.
709
- if (toAdd.length) {
710
- if (sortable) sort = true;
711
- this.length += toAdd.length;
712
- if (at != null) {
713
- splice.apply(this.models, [at, 0].concat(toAdd));
714
- } else {
715
- push.apply(this.models, toAdd);
716
- }
717
- }
718
-
719
- // Silently sort the collection if appropriate.
720
- if (sort) this.sort({silent: true});
721
-
722
- if (options.silent) return this;
723
-
724
- // Trigger `add` events.
725
- for (i = 0, l = toAdd.length; i < l; i++) {
726
- (model = toAdd[i]).trigger('add', model, this, options);
727
- }
728
-
729
- // Trigger `sort` if the collection was sorted.
730
- if (sort) this.trigger('sort', this, options);
731
- return this;
732
- },
733
-
734
- // When you have more items than you want to add or remove individually,
735
- // you can reset the entire set with a new list of models, without firing
736
- // any granular `add` or `remove` events. Fires `reset` when finished.
737
- // Useful for bulk operations and optimizations.
738
- reset: function(models, options) {
739
- options || (options = {});
740
- for (var i = 0, l = this.models.length; i < l; i++) {
741
- this._removeReference(this.models[i]);
742
- }
743
- options.previousModels = this.models;
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
- // Add a model to the end of the collection.
751
- push: function(model, options) {
752
- model = this._prepareModel(model, options);
753
- this.add(model, _.extend({at: this.length}, options));
754
- return model;
755
- },
756
-
757
- // Remove a model from the end of the collection.
758
- pop: function(options) {
759
- var model = this.at(this.length - 1);
760
- this.remove(model, options);
761
- return model;
762
- },
763
-
764
- // Add a model to the beginning of the collection.
765
- unshift: function(model, options) {
766
- model = this._prepareModel(model, options);
767
- this.add(model, _.extend({at: 0}, options));
768
- return model;
769
- },
770
-
771
- // Remove a model from the beginning of the collection.
772
- shift: function(options) {
773
- var model = this.at(0);
774
- this.remove(model, options);
775
- return model;
776
- },
777
-
778
- // Slice out a sub-array of models from the collection.
779
- slice: function(begin, end) {
780
- return this.models.slice(begin, end);
781
- },
782
-
783
- // Get a model from the set by id.
784
- get: function(obj) {
785
- if (obj == null) return void 0;
786
- return this._byId[obj.id != null ? obj.id : obj.cid || obj];
787
- },
788
-
789
- // Get the model at the given index.
790
- at: function(index) {
791
- return this.models[index];
792
- },
793
-
794
- // Return models with matching attributes. Useful for simple cases of
795
- // `filter`.
796
- where: function(attrs, first) {
797
- if (_.isEmpty(attrs)) return first ? void 0 : [];
798
- return this[first ? 'find' : 'filter'](function(model) {
799
- for (var key in attrs) {
800
- if (attrs[key] !== model.get(key)) return false;
801
- }
802
- return true;
803
- });
804
- },
805
-
806
- // Return the first model with matching attributes. Useful for simple cases
807
- // of `find`.
808
- findWhere: function(attrs) {
809
- return this.where(attrs, true);
810
- },
811
-
812
- // Force the collection to re-sort itself. You don't need to call this under
813
- // normal circumstances, as the set will maintain sort order as each item
814
- // is added.
815
- sort: function(options) {
816
- if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
817
- options || (options = {});
818
-
819
- // Run sort based on type of `comparator`.
820
- if (_.isString(this.comparator) || this.comparator.length === 1) {
821
- this.models = this.sortBy(this.comparator, this);
822
- } else {
823
- this.models.sort(_.bind(this.comparator, this));
824
- }
825
-
826
- if (!options.silent) this.trigger('sort', this, options);
827
- return this;
828
- },
829
-
830
- // Figure out the smallest index at which a model should be inserted so as
831
- // to maintain order.
832
- sortedIndex: function(model, value, context) {
833
- value || (value = this.comparator);
834
- var iterator = _.isFunction(value) ? value : function(model) {
835
- return model.get(value);
836
- };
837
- return _.sortedIndex(this.models, model, iterator, context);
838
- },
839
-
840
- // Pluck an attribute from each model in the collection.
841
- pluck: function(attr) {
842
- return _.invoke(this.models, 'get', attr);
843
- },
844
-
845
- // Fetch the default set of models for this collection, resetting the
846
- // collection when they arrive. If `reset: true` is passed, the response
847
- // data will be passed through the `reset` method instead of `set`.
848
- fetch: function(options) {
849
- options = options ? _.clone(options) : {};
850
- if (options.parse === void 0) options.parse = true;
851
- var success = options.success;
852
- var collection = this;
853
- options.success = function(resp) {
854
- var method = options.reset ? 'reset' : 'set';
855
- collection[method](resp, options);
856
- if (success) success(collection, resp, options);
857
- collection.trigger('sync', collection, resp, options);
858
- };
859
- wrapError(this, options);
860
- return this.sync('read', this, options);
861
- },
862
-
863
- // Create a new instance of a model in this collection. Add the model to the
864
- // collection immediately, unless `wait: true` is passed, in which case we
865
- // wait for the server to agree.
866
- create: function(model, options) {
867
- options = options ? _.clone(options) : {};
868
- if (!(model = this._prepareModel(model, options))) return false;
869
- if (!options.wait) this.add(model, options);
870
- var collection = this;
871
- var success = options.success;
872
- options.success = function(resp) {
873
- if (options.wait) collection.add(model, options);
874
- if (success) success(model, resp, options);
875
- };
876
- model.save(null, options);
877
- return model;
878
- },
879
-
880
- // **parse** converts a response into a list of models to be added to the
881
- // collection. The default implementation is just to pass it through.
882
- parse: function(resp, options) {
883
- return resp;
884
- },
885
-
886
- // Create a new collection with an identical list of models as this one.
887
- clone: function() {
888
- return new this.constructor(this.models);
889
- },
890
-
891
- // Private method to reset all internal state. Called when the collection
892
- // is first initialized or reset.
893
- _reset: function() {
894
- this.length = 0;
895
- this.models = [];
896
- this._byId = {};
897
- },
898
-
899
- // Prepare a hash of attributes (or other model) to be added to this
900
- // collection.
901
- _prepareModel: function(attrs, options) {
902
- if (attrs instanceof Model) {
903
- if (!attrs.collection) attrs.collection = this;
904
- return attrs;
905
- }
906
- options || (options = {});
907
- options.collection = this;
908
- var model = new this.model(attrs, options);
909
- if (!model._validate(attrs, options)) {
910
- this.trigger('invalid', this, attrs, options);
911
- return false;
912
- }
913
- return model;
914
- },
915
-
916
- // Internal method to sever a model's ties to a collection.
917
- _removeReference: function(model) {
918
- if (this === model.collection) delete model.collection;
919
- model.off('all', this._onModelEvent, this);
920
- },
921
-
922
- // Internal method called every time a model in the set fires an event.
923
- // Sets need to update their indexes when models change ids. All other
924
- // events simply proxy through. "add" and "remove" events that originate
925
- // in other collections are ignored.
926
- _onModelEvent: function(event, model, collection, options) {
927
- if ((event === 'add' || event === 'remove') && collection !== this) return;
928
- if (event === 'destroy') this.remove(model, options);
929
- if (model && event === 'change:' + model.idAttribute) {
930
- delete this._byId[model.previous(model.idAttribute)];
931
- if (model.id != null) this._byId[model.id] = model;
932
- }
933
- this.trigger.apply(this, arguments);
934
- }
935
-
936
- });
937
-
938
- // Underscore methods that we want to implement on the Collection.
939
- // 90% of the core usefulness of Backbone Collections is actually implemented
940
- // right here:
941
- var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
942
- 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
943
- 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
944
- 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
945
- 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
946
- 'isEmpty', 'chain'];
947
-
948
- // Mix in each Underscore method as a proxy to `Collection#models`.
949
- _.each(methods, function(method) {
950
- Collection.prototype[method] = function() {
951
- var args = slice.call(arguments);
952
- args.unshift(this.models);
953
- return _[method].apply(_, args);
954
- };
955
- });
956
-
957
- // Underscore methods that take a property name as an argument.
958
- var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
959
-
960
- // Use attributes instead of properties.
961
- _.each(attributeMethods, function(method) {
962
- Collection.prototype[method] = function(value, context) {
963
- var iterator = _.isFunction(value) ? value : function(model) {
964
- return model.get(value);
965
- };
966
- return _[method](this.models, iterator, context);
967
- };
968
- });
969
-
970
- // Backbone.View
971
- // -------------
972
-
973
- // Backbone Views are almost more convention than they are actual code. A View
974
- // is simply a JavaScript object that represents a logical chunk of UI in the
975
- // DOM. This might be a single item, an entire list, a sidebar or panel, or
976
- // even the surrounding frame which wraps your whole app. Defining a chunk of
977
- // UI as a **View** allows you to define your DOM events declaratively, without
978
- // having to worry about render order ... and makes it easy for the view to
979
- // react to specific changes in the state of your models.
980
-
981
- // Creating a Backbone.View creates its initial element outside of the DOM,
982
- // if an existing element is not provided...
983
- var View = Backbone.View = function(options) {
984
- this.cid = _.uniqueId('view');
985
- this._configure(options || {});
986
- this._ensureElement();
987
- this.initialize.apply(this, arguments);
988
- this.delegateEvents();
989
- };
990
-
991
- // Cached regex to split keys for `delegate`.
992
- var delegateEventSplitter = /^(\S+)\s*(.*)$/;
993
-
994
- // List of view options to be merged as properties.
995
- var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
996
-
997
- // Set up all inheritable **Backbone.View** properties and methods.
998
- _.extend(View.prototype, Events, {
999
-
1000
- // The default `tagName` of a View's element is `"div"`.
1001
- tagName: 'div',
1002
-
1003
- // jQuery delegate for element lookup, scoped to DOM elements within the
1004
- // current view. This should be prefered to global lookups where possible.
1005
- $: function(selector) {
1006
- return this.$el.find(selector);
1007
- },
1008
-
1009
- // Initialize is an empty function by default. Override it with your own
1010
- // initialization logic.
1011
- initialize: function(){},
1012
-
1013
- // **render** is the core function that your view should override, in order
1014
- // to populate its element (`this.el`), with the appropriate HTML. The
1015
- // convention is for **render** to always return `this`.
1016
- render: function() {
1017
- return this;
1018
- },
1019
-
1020
- // Remove this view by taking the element out of the DOM, and removing any
1021
- // applicable Backbone.Events listeners.
1022
- remove: function() {
1023
- this.$el.remove();
1024
- this.stopListening();
1025
- return this;
1026
- },
1027
-
1028
- // Change the view's element (`this.el` property), including event
1029
- // re-delegation.
1030
- setElement: function(element, delegate) {
1031
- if (this.$el) this.undelegateEvents();
1032
- this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1033
- this.el = this.$el[0];
1034
- if (delegate !== false) this.delegateEvents();
1035
- return this;
1036
- },
1037
-
1038
- // Set callbacks, where `this.events` is a hash of
1039
- //
1040
- // *{"event selector": "callback"}*
1041
- //
1042
- // {
1043
- // 'mousedown .title': 'edit',
1044
- // 'click .button': 'save'
1045
- // 'click .open': function(e) { ... }
1046
- // }
1047
- //
1048
- // pairs. Callbacks will be bound to the view, with `this` set properly.
1049
- // Uses event delegation for efficiency.
1050
- // Omitting the selector binds the event to `this.el`.
1051
- // This only works for delegate-able events: not `focus`, `blur`, and
1052
- // not `change`, `submit`, and `reset` in Internet Explorer.
1053
- delegateEvents: function(events) {
1054
- if (!(events || (events = _.result(this, 'events')))) return this;
1055
- this.undelegateEvents();
1056
- for (var key in events) {
1057
- var method = events[key];
1058
- if (!_.isFunction(method)) method = this[events[key]];
1059
- if (!method) continue;
1060
-
1061
- var match = key.match(delegateEventSplitter);
1062
- var eventName = match[1], selector = match[2];
1063
- method = _.bind(method, this);
1064
- eventName += '.delegateEvents' + this.cid;
1065
- if (selector === '') {
1066
- this.$el.on(eventName, method);
1067
- } else {
1068
- this.$el.on(eventName, selector, method);
1069
- }
1070
- }
1071
- return this;
1072
- },
1073
-
1074
- // Clears all callbacks previously bound to the view with `delegateEvents`.
1075
- // You usually don't need to use this, but may wish to if you have multiple
1076
- // Backbone views attached to the same DOM element.
1077
- undelegateEvents: function() {
1078
- this.$el.off('.delegateEvents' + this.cid);
1079
- return this;
1080
- },
1081
-
1082
- // Performs the initial configuration of a View with a set of options.
1083
- // Keys with special meaning *(e.g. model, collection, id, className)* are
1084
- // attached directly to the view. See `viewOptions` for an exhaustive
1085
- // list.
1086
- _configure: function(options) {
1087
- if (this.options) options = _.extend({}, _.result(this, 'options'), options);
1088
- _.extend(this, _.pick(options, viewOptions));
1089
- this.options = options;
1090
- },
1091
-
1092
- // Ensure that the View has a DOM element to render into.
1093
- // If `this.el` is a string, pass it through `$()`, take the first
1094
- // matching element, and re-assign it to `el`. Otherwise, create
1095
- // an element from the `id`, `className` and `tagName` properties.
1096
- _ensureElement: function() {
1097
- if (!this.el) {
1098
- var attrs = _.extend({}, _.result(this, 'attributes'));
1099
- if (this.id) attrs.id = _.result(this, 'id');
1100
- if (this.className) attrs['class'] = _.result(this, 'className');
1101
- var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1102
- this.setElement($el, false);
1103
- } else {
1104
- this.setElement(_.result(this, 'el'), false);
1105
- }
1106
- }
1107
-
1108
- });
1109
-
1110
- // Backbone.sync
1111
- // -------------
1112
-
1113
- // Override this function to change the manner in which Backbone persists
1114
- // models to the server. You will be passed the type of request, and the
1115
- // model in question. By default, makes a RESTful Ajax request
1116
- // to the model's `url()`. Some possible customizations could be:
1117
- //
1118
- // * Use `setTimeout` to batch rapid-fire updates into a single request.
1119
- // * Send up the models as XML instead of JSON.
1120
- // * Persist models via WebSockets instead of Ajax.
1121
- //
1122
- // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1123
- // as `POST`, with a `_method` parameter containing the true HTTP method,
1124
- // as well as all requests with the body as `application/x-www-form-urlencoded`
1125
- // instead of `application/json` with the model in a param named `model`.
1126
- // Useful when interfacing with server-side languages like **PHP** that make
1127
- // it difficult to read the body of `PUT` requests.
1128
- Backbone.sync = function(method, model, options) {
1129
- var type = methodMap[method];
1130
-
1131
- // Default options, unless specified.
1132
- _.defaults(options || (options = {}), {
1133
- emulateHTTP: Backbone.emulateHTTP,
1134
- emulateJSON: Backbone.emulateJSON
1135
- });
1136
-
1137
- // Default JSON-request options.
1138
- var params = {type: type, dataType: 'json'};
1139
-
1140
- // Ensure that we have a URL.
1141
- if (!options.url) {
1142
- params.url = _.result(model, 'url') || urlError();
1143
- }
1144
-
1145
- // Ensure that we have the appropriate request data.
1146
- if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1147
- params.contentType = 'application/json';
1148
- params.data = JSON.stringify(options.attrs || model.toJSON(options));
1149
- }
1150
-
1151
- // For older servers, emulate JSON by encoding the request into an HTML-form.
1152
- if (options.emulateJSON) {
1153
- params.contentType = 'application/x-www-form-urlencoded';
1154
- params.data = params.data ? {model: params.data} : {};
1155
- }
1156
-
1157
- // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1158
- // And an `X-HTTP-Method-Override` header.
1159
- if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1160
- params.type = 'POST';
1161
- if (options.emulateJSON) params.data._method = type;
1162
- var beforeSend = options.beforeSend;
1163
- options.beforeSend = function(xhr) {
1164
- xhr.setRequestHeader('X-HTTP-Method-Override', type);
1165
- if (beforeSend) return beforeSend.apply(this, arguments);
1166
- };
1167
- }
1168
-
1169
- // Don't process data on a non-GET request.
1170
- if (params.type !== 'GET' && !options.emulateJSON) {
1171
- params.processData = false;
1172
- }
1173
-
1174
- // If we're sending a `PATCH` request, and we're in an old Internet Explorer
1175
- // that still has ActiveX enabled by default, override jQuery to use that
1176
- // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
1177
- if (params.type === 'PATCH' && window.ActiveXObject &&
1178
- !(window.external && window.external.msActiveXFilteringEnabled)) {
1179
- params.xhr = function() {
1180
- return new ActiveXObject("Microsoft.XMLHTTP");
1181
- };
1182
- }
1183
-
1184
- // Make the request, allowing the user to override any Ajax options.
1185
- var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1186
- model.trigger('request', model, xhr, options);
1187
- return xhr;
1188
- };
1189
-
1190
- // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1191
- var methodMap = {
1192
- 'create': 'POST',
1193
- 'update': 'PUT',
1194
- 'patch': 'PATCH',
1195
- 'delete': 'DELETE',
1196
- 'read': 'GET'
1197
- };
1198
-
1199
- // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1200
- // Override this if you'd like to use a different library.
1201
- Backbone.ajax = function() {
1202
- return Backbone.$.ajax.apply(Backbone.$, arguments);
1203
- };
1204
-
1205
- // Backbone.Router
1206
- // ---------------
1207
-
1208
- // Routers map faux-URLs to actions, and fire events when routes are
1209
- // matched. Creating a new one sets its `routes` hash, if not set statically.
1210
- var Router = Backbone.Router = function(options) {
1211
- options || (options = {});
1212
- if (options.routes) this.routes = options.routes;
1213
- this._bindRoutes();
1214
- this.initialize.apply(this, arguments);
1215
- };
1216
-
1217
- // Cached regular expressions for matching named param parts and splatted
1218
- // parts of route strings.
1219
- var optionalParam = /\((.*?)\)/g;
1220
- var namedParam = /(\(\?)?:\w+/g;
1221
- var splatParam = /\*\w+/g;
1222
- var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1223
-
1224
- // Set up all inheritable **Backbone.Router** properties and methods.
1225
- _.extend(Router.prototype, Events, {
1226
-
1227
- // Initialize is an empty function by default. Override it with your own
1228
- // initialization logic.
1229
- initialize: function(){},
1230
-
1231
- // Manually bind a single named route to a callback. For example:
1232
- //
1233
- // this.route('search/:query/p:num', 'search', function(query, num) {
1234
- // ...
1235
- // });
1236
- //
1237
- route: function(route, name, callback) {
1238
- if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1239
- if (_.isFunction(name)) {
1240
- callback = name;
1241
- name = '';
1242
- }
1243
- if (!callback) callback = this[name];
1244
- var router = this;
1245
- Backbone.history.route(route, function(fragment) {
1246
- var args = router._extractParameters(route, fragment);
1247
- callback && callback.apply(router, args);
1248
- router.trigger.apply(router, ['route:' + name].concat(args));
1249
- router.trigger('route', name, args);
1250
- Backbone.history.trigger('route', router, name, args);
1251
- });
1252
- return this;
1253
- },
1254
-
1255
- // Simple proxy to `Backbone.history` to save a fragment into the history.
1256
- navigate: function(fragment, options) {
1257
- Backbone.history.navigate(fragment, options);
1258
- return this;
1259
- },
1260
-
1261
- // Bind all defined routes to `Backbone.history`. We have to reverse the
1262
- // order of the routes here to support behavior where the most general
1263
- // routes can be defined at the bottom of the route map.
1264
- _bindRoutes: function() {
1265
- if (!this.routes) return;
1266
- this.routes = _.result(this, 'routes');
1267
- var route, routes = _.keys(this.routes);
1268
- while ((route = routes.pop()) != null) {
1269
- this.route(route, this.routes[route]);
1270
- }
1271
- },
1272
-
1273
- // Convert a route string into a regular expression, suitable for matching
1274
- // against the current location hash.
1275
- _routeToRegExp: function(route) {
1276
- route = route.replace(escapeRegExp, '\\$&')
1277
- .replace(optionalParam, '(?:$1)?')
1278
- .replace(namedParam, function(match, optional){
1279
- return optional ? match : '([^\/]+)';
1280
- })
1281
- .replace(splatParam, '(.*?)');
1282
- return new RegExp('^' + route + '$');
1283
- },
1284
-
1285
- // Given a route, and a URL fragment that it matches, return the array of
1286
- // extracted decoded parameters. Empty or unmatched parameters will be
1287
- // treated as `null` to normalize cross-browser behavior.
1288
- _extractParameters: function(route, fragment) {
1289
- var params = route.exec(fragment).slice(1);
1290
- return _.map(params, function(param) {
1291
- return param ? decodeURIComponent(param) : null;
1292
- });
1293
- }
1294
-
1295
- });
1296
-
1297
- // Backbone.History
1298
- // ----------------
1299
-
1300
- // Handles cross-browser history management, based on either
1301
- // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1302
- // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1303
- // and URL fragments. If the browser supports neither (old IE, natch),
1304
- // falls back to polling.
1305
- var History = Backbone.History = function() {
1306
- this.handlers = [];
1307
- _.bindAll(this, 'checkUrl');
1308
-
1309
- // Ensure that `History` can be used outside of the browser.
1310
- if (typeof window !== 'undefined') {
1311
- this.location = window.location;
1312
- this.history = window.history;
1313
- }
1314
- };
1315
-
1316
- // Cached regex for stripping a leading hash/slash and trailing space.
1317
- var routeStripper = /^[#\/]|\s+$/g;
1318
-
1319
- // Cached regex for stripping leading and trailing slashes.
1320
- var rootStripper = /^\/+|\/+$/g;
1321
-
1322
- // Cached regex for detecting MSIE.
1323
- var isExplorer = /msie [\w.]+/;
1324
-
1325
- // Cached regex for removing a trailing slash.
1326
- var trailingSlash = /\/$/;
1327
-
1328
- // Has the history handling already been started?
1329
- History.started = false;
1330
-
1331
- // Set up all inheritable **Backbone.History** properties and methods.
1332
- _.extend(History.prototype, Events, {
1333
-
1334
- // The default interval to poll for hash changes, if necessary, is
1335
- // twenty times a second.
1336
- interval: 50,
1337
-
1338
- // Gets the true hash value. Cannot use location.hash directly due to bug
1339
- // in Firefox where location.hash will always be decoded.
1340
- getHash: function(window) {
1341
- var match = (window || this).location.href.match(/#(.*)$/);
1342
- return match ? match[1] : '';
1343
- },
1344
-
1345
- // Get the cross-browser normalized URL fragment, either from the URL,
1346
- // the hash, or the override.
1347
- getFragment: function(fragment, forcePushState) {
1348
- if (fragment == null) {
1349
- if (this._hasPushState || !this._wantsHashChange || forcePushState) {
1350
- fragment = this.location.pathname;
1351
- var root = this.root.replace(trailingSlash, '');
1352
- if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
1353
- } else {
1354
- fragment = this.getHash();
1355
- }
1356
- }
1357
- return fragment.replace(routeStripper, '');
1358
- },
1359
-
1360
- // Start the hash change handling, returning `true` if the current URL matches
1361
- // an existing route, and `false` otherwise.
1362
- start: function(options) {
1363
- if (History.started) throw new Error("Backbone.history has already been started");
1364
- History.started = true;
1365
-
1366
- // Figure out the initial configuration. Do we need an iframe?
1367
- // Is pushState desired ... is it available?
1368
- this.options = _.extend({}, {root: '/'}, this.options, options);
1369
- this.root = this.options.root;
1370
- this._wantsHashChange = this.options.hashChange !== false;
1371
- this._wantsPushState = !!this.options.pushState;
1372
- this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
1373
- var fragment = this.getFragment();
1374
- var docMode = document.documentMode;
1375
- var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
1376
-
1377
- // Normalize root to always include a leading and trailing slash.
1378
- this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1379
-
1380
- if (oldIE && this._wantsHashChange) {
1381
- this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
1382
- this.navigate(fragment);
1383
- }
1384
-
1385
- // Depending on whether we're using pushState or hashes, and whether
1386
- // 'onhashchange' is supported, determine how we check the URL state.
1387
- if (this._hasPushState) {
1388
- Backbone.$(window).on('popstate', this.checkUrl);
1389
- } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
1390
- Backbone.$(window).on('hashchange', this.checkUrl);
1391
- } else if (this._wantsHashChange) {
1392
- this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1393
- }
1394
-
1395
- // Determine if we need to change the base url, for a pushState link
1396
- // opened by a non-pushState browser.
1397
- this.fragment = fragment;
1398
- var loc = this.location;
1399
- var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
1400
-
1401
- // If we've started off with a route from a `pushState`-enabled browser,
1402
- // but we're currently in a browser that doesn't support it...
1403
- if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
1404
- this.fragment = this.getFragment(null, true);
1405
- this.location.replace(this.root + this.location.search + '#' + this.fragment);
1406
- // Return immediately as browser will do redirect to new url
1407
- return true;
1408
-
1409
- // Or if we've started out with a hash-based route, but we're currently
1410
- // in a browser where it could be `pushState`-based instead...
1411
- } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
1412
- this.fragment = this.getHash().replace(routeStripper, '');
1413
- this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1414
- }
1415
-
1416
- if (!this.options.silent) return this.loadUrl();
1417
- },
1418
-
1419
- // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1420
- // but possibly useful for unit testing Routers.
1421
- stop: function() {
1422
- Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1423
- clearInterval(this._checkUrlInterval);
1424
- History.started = false;
1425
- },
1426
-
1427
- // Add a route to be tested when the fragment changes. Routes added later
1428
- // may override previous routes.
1429
- route: function(route, callback) {
1430
- this.handlers.unshift({route: route, callback: callback});
1431
- },
1432
-
1433
- // Checks the current URL to see if it has changed, and if it has,
1434
- // calls `loadUrl`, normalizing across the hidden iframe.
1435
- checkUrl: function(e) {
1436
- var current = this.getFragment();
1437
- if (current === this.fragment && this.iframe) {
1438
- current = this.getFragment(this.getHash(this.iframe));
1439
- }
1440
- if (current === this.fragment) return false;
1441
- if (this.iframe) this.navigate(current);
1442
- this.loadUrl() || this.loadUrl(this.getHash());
1443
- },
1444
-
1445
- // Attempt to load the current URL fragment. If a route succeeds with a
1446
- // match, returns `true`. If no defined routes matches the fragment,
1447
- // returns `false`.
1448
- loadUrl: function(fragmentOverride) {
1449
- var fragment = this.fragment = this.getFragment(fragmentOverride);
1450
- var matched = _.any(this.handlers, function(handler) {
1451
- if (handler.route.test(fragment)) {
1452
- handler.callback(fragment);
1453
- return true;
1454
- }
1455
- });
1456
- return matched;
1457
- },
1458
-
1459
- // Save a fragment into the hash history, or replace the URL state if the
1460
- // 'replace' option is passed. You are responsible for properly URL-encoding
1461
- // the fragment in advance.
1462
- //
1463
- // The options object can contain `trigger: true` if you wish to have the
1464
- // route callback be fired (not usually desirable), or `replace: true`, if
1465
- // you wish to modify the current URL without adding an entry to the history.
1466
- navigate: function(fragment, options) {
1467
- if (!History.started) return false;
1468
- if (!options || options === true) options = {trigger: options};
1469
- fragment = this.getFragment(fragment || '');
1470
- if (this.fragment === fragment) return;
1471
- this.fragment = fragment;
1472
- var url = this.root + fragment;
1473
-
1474
- // If pushState is available, we use it to set the fragment as a real URL.
1475
- if (this._hasPushState) {
1476
- this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1477
-
1478
- // If hash changes haven't been explicitly disabled, update the hash
1479
- // fragment to store history.
1480
- } else if (this._wantsHashChange) {
1481
- this._updateHash(this.location, fragment, options.replace);
1482
- if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1483
- // Opening and closing the iframe tricks IE7 and earlier to push a
1484
- // history entry on hash-tag change. When replace is true, we don't
1485
- // want this.
1486
- if(!options.replace) this.iframe.document.open().close();
1487
- this._updateHash(this.iframe.location, fragment, options.replace);
1488
- }
1489
-
1490
- // If you've told us that you explicitly don't want fallback hashchange-
1491
- // based history, then `navigate` becomes a page refresh.
1492
- } else {
1493
- return this.location.assign(url);
1494
- }
1495
- if (options.trigger) this.loadUrl(fragment);
1496
- },
1497
-
1498
- // Update the hash location, either replacing the current entry, or adding
1499
- // a new one to the browser history.
1500
- _updateHash: function(location, fragment, replace) {
1501
- if (replace) {
1502
- var href = location.href.replace(/(javascript:|#).*$/, '');
1503
- location.replace(href + '#' + fragment);
1504
- } else {
1505
- // Some browsers require that `hash` contains a leading #.
1506
- location.hash = '#' + fragment;
1507
- }
1508
- }
1509
-
1510
- });
1511
-
1512
- // Create the default Backbone.history.
1513
- Backbone.history = new History;
1514
-
1515
- // Helpers
1516
- // -------
1517
-
1518
- // Helper function to correctly set up the prototype chain, for subclasses.
1519
- // Similar to `goog.inherits`, but uses a hash of prototype properties and
1520
- // class properties to be extended.
1521
- var extend = function(protoProps, staticProps) {
1522
- var parent = this;
1523
- var child;
1524
-
1525
- // The constructor function for the new subclass is either defined by you
1526
- // (the "constructor" property in your `extend` definition), or defaulted
1527
- // by us to simply call the parent's constructor.
1528
- if (protoProps && _.has(protoProps, 'constructor')) {
1529
- child = protoProps.constructor;
1530
- } else {
1531
- child = function(){ return parent.apply(this, arguments); };
1532
- }
1533
-
1534
- // Add static properties to the constructor function, if supplied.
1535
- _.extend(child, parent, staticProps);
1536
-
1537
- // Set the prototype chain to inherit from `parent`, without calling
1538
- // `parent`'s constructor function.
1539
- var Surrogate = function(){ this.constructor = child; };
1540
- Surrogate.prototype = parent.prototype;
1541
- child.prototype = new Surrogate;
1542
-
1543
- // Add prototype properties (instance properties) to the subclass,
1544
- // if supplied.
1545
- if (protoProps) _.extend(child.prototype, protoProps);
1546
-
1547
- // Set a convenience property in case the parent's prototype is needed
1548
- // later.
1549
- child.__super__ = parent.prototype;
1550
-
1551
- return child;
1552
- };
1553
-
1554
- // Set up inheritance for the model, collection, router, view and history.
1555
- Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1556
-
1557
- // Throw an error when a URL is needed, and none is supplied.
1558
- var urlError = function() {
1559
- throw new Error('A "url" property or function must be specified');
1560
- };
1561
-
1562
- // Wrap an optional error callback with a fallback error event.
1563
- var wrapError = function (model, options) {
1564
- var error = options.error;
1565
- options.error = function(resp) {
1566
- if (error) error(model, resp, options);
1567
- model.trigger('error', model, resp, options);
1568
- };
1569
- };
1570
-
1571
- }).call(this);
1572
-
1573
- // Backbone.BabySitter
1574
- // -------------------
1575
- // v0.0.6
1576
- //
1577
- // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1578
- // Distributed under MIT license
1579
- //
1580
- // http://github.com/babysitterjs/backbone.babysitter
1581
-
1582
- // Backbone.ChildViewContainer
1583
- // ---------------------------
1584
- //
1585
- // Provide a container to store, retrieve and
1586
- // shut down child views.
1587
-
1588
- Backbone.ChildViewContainer = (function(Backbone, _){
1589
-
1590
- // Container Constructor
1591
- // ---------------------
1592
-
1593
- var Container = function(views){
1594
- this._views = {};
1595
- this._indexByModel = {};
1596
- this._indexByCustom = {};
1597
- this._updateLength();
1598
-
1599
- _.each(views, this.add, this);
1600
- };
1601
-
1602
- // Container Methods
1603
- // -----------------
1604
-
1605
- _.extend(Container.prototype, {
1606
-
1607
- // Add a view to this container. Stores the view
1608
- // by `cid` and makes it searchable by the model
1609
- // cid (and model itself). Optionally specify
1610
- // a custom key to store an retrieve the view.
1611
- add: function(view, customIndex){
1612
- var viewCid = view.cid;
1613
-
1614
- // store the view
1615
- this._views[viewCid] = view;
1616
-
1617
- // index it by model
1618
- if (view.model){
1619
- this._indexByModel[view.model.cid] = viewCid;
1620
- }
1621
-
1622
- // index by custom
1623
- if (customIndex){
1624
- this._indexByCustom[customIndex] = viewCid;
1625
- }
1626
-
1627
- this._updateLength();
1628
- },
1629
-
1630
- // Find a view by the model that was attached to
1631
- // it. Uses the model's `cid` to find it.
1632
- findByModel: function(model){
1633
- return this.findByModelCid(model.cid);
1634
- },
1635
-
1636
- // Find a view by the `cid` of the model that was attached to
1637
- // it. Uses the model's `cid` to find the view `cid` and
1638
- // retrieve the view using it.
1639
- findByModelCid: function(modelCid){
1640
- var viewCid = this._indexByModel[modelCid];
1641
- return this.findByCid(viewCid);
1642
- },
1643
-
1644
- // Find a view by a custom indexer.
1645
- findByCustom: function(index){
1646
- var viewCid = this._indexByCustom[index];
1647
- return this.findByCid(viewCid);
1648
- },
1649
-
1650
- // Find by index. This is not guaranteed to be a
1651
- // stable index.
1652
- findByIndex: function(index){
1653
- return _.values(this._views)[index];
1654
- },
1655
-
1656
- // retrieve a view by it's `cid` directly
1657
- findByCid: function(cid){
1658
- return this._views[cid];
1659
- },
1660
-
1661
- // Remove a view
1662
- remove: function(view){
1663
- var viewCid = view.cid;
1664
-
1665
- // delete model index
1666
- if (view.model){
1667
- delete this._indexByModel[view.model.cid];
1668
- }
1669
-
1670
- // delete custom index
1671
- _.any(this._indexByCustom, function(cid, key) {
1672
- if (cid === viewCid) {
1673
- delete this._indexByCustom[key];
1674
- return true;
1675
- }
1676
- }, this);
1677
-
1678
- // remove the view from the container
1679
- delete this._views[viewCid];
1680
-
1681
- // update the length
1682
- this._updateLength();
1683
- },
1684
-
1685
- // Call a method on every view in the container,
1686
- // passing parameters to the call method one at a
1687
- // time, like `function.call`.
1688
- call: function(method){
1689
- this.apply(method, _.tail(arguments));
1690
- },
1691
-
1692
- // Apply a method on every view in the container,
1693
- // passing parameters to the call method one at a
1694
- // time, like `function.apply`.
1695
- apply: function(method, args){
1696
- _.each(this._views, function(view){
1697
- if (_.isFunction(view[method])){
1698
- view[method].apply(view, args || []);
1699
- }
1700
- });
1701
- },
1702
-
1703
- // Update the `.length` attribute on this container
1704
- _updateLength: function(){
1705
- this.length = _.size(this._views);
1706
- }
1707
- });
1708
-
1709
- // Borrowing this code from Backbone.Collection:
1710
- // http://backbonejs.org/docs/backbone.html#section-106
1711
- //
1712
- // Mix in methods from Underscore, for iteration, and other
1713
- // collection related features.
1714
- var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
1715
- 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
1716
- 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
1717
- 'last', 'without', 'isEmpty', 'pluck'];
1718
-
1719
- _.each(methods, function(method) {
1720
- Container.prototype[method] = function() {
1721
- var views = _.values(this._views);
1722
- var args = [views].concat(_.toArray(arguments));
1723
- return _[method].apply(_, args);
1724
- };
1725
- });
1726
-
1727
- // return the public API
1728
- return Container;
1729
- })(Backbone, _);
1730
-
1731
- // Backbone.Wreqr (Backbone.Marionette)
1732
- // ----------------------------------
1733
- // v0.2.0
1734
- //
1735
- // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1736
- // Distributed under MIT license
1737
- //
1738
- // http://github.com/marionettejs/backbone.wreqr
1739
-
1740
-
1741
- Backbone.Wreqr = (function(Backbone, Marionette, _){
1742
- "use strict";
1743
- var Wreqr = {};
1744
-
1745
- // Handlers
1746
- // --------
1747
- // A registry of functions to call, given a name
1748
-
1749
- Wreqr.Handlers = (function(Backbone, _){
1750
- "use strict";
1751
-
1752
- // Constructor
1753
- // -----------
1754
-
1755
- var Handlers = function(options){
1756
- this.options = options;
1757
- this._wreqrHandlers = {};
1758
-
1759
- if (_.isFunction(this.initialize)){
1760
- this.initialize(options);
1761
- }
1762
- };
1763
-
1764
- Handlers.extend = Backbone.Model.extend;
1765
-
1766
- // Instance Members
1767
- // ----------------
1768
-
1769
- _.extend(Handlers.prototype, Backbone.Events, {
1770
-
1771
- // Add multiple handlers using an object literal configuration
1772
- setHandlers: function(handlers){
1773
- _.each(handlers, function(handler, name){
1774
- var context = null;
1775
-
1776
- if (_.isObject(handler) && !_.isFunction(handler)){
1777
- context = handler.context;
1778
- handler = handler.callback;
1779
- }
1780
-
1781
- this.setHandler(name, handler, context);
1782
- }, this);
1783
- },
1784
-
1785
- // Add a handler for the given name, with an
1786
- // optional context to run the handler within
1787
- setHandler: function(name, handler, context){
1788
- var config = {
1789
- callback: handler,
1790
- context: context
1791
- };
1792
-
1793
- this._wreqrHandlers[name] = config;
1794
-
1795
- this.trigger("handler:add", name, handler, context);
1796
- },
1797
-
1798
- // Determine whether or not a handler is registered
1799
- hasHandler: function(name){
1800
- return !! this._wreqrHandlers[name];
1801
- },
1802
-
1803
- // Get the currently registered handler for
1804
- // the specified name. Throws an exception if
1805
- // no handler is found.
1806
- getHandler: function(name){
1807
- var config = this._wreqrHandlers[name];
1808
-
1809
- if (!config){
1810
- throw new Error("Handler not found for '" + name + "'");
1811
- }
1812
-
1813
- return function(){
1814
- var args = Array.prototype.slice.apply(arguments);
1815
- return config.callback.apply(config.context, args);
1816
- };
1817
- },
1818
-
1819
- // Remove a handler for the specified name
1820
- removeHandler: function(name){
1821
- delete this._wreqrHandlers[name];
1822
- },
1823
-
1824
- // Remove all handlers from this registry
1825
- removeAllHandlers: function(){
1826
- this._wreqrHandlers = {};
1827
- }
1828
- });
1829
-
1830
- return Handlers;
1831
- })(Backbone, _);
1832
-
1833
- // Wreqr.CommandStorage
1834
- // --------------------
1835
- //
1836
- // Store and retrieve commands for execution.
1837
- Wreqr.CommandStorage = (function(){
1838
- "use strict";
1839
-
1840
- // Constructor function
1841
- var CommandStorage = function(options){
1842
- this.options = options;
1843
- this._commands = {};
1844
-
1845
- if (_.isFunction(this.initialize)){
1846
- this.initialize(options);
1847
- }
1848
- };
1849
-
1850
- // Instance methods
1851
- _.extend(CommandStorage.prototype, Backbone.Events, {
1852
-
1853
- // Get an object literal by command name, that contains
1854
- // the `commandName` and the `instances` of all commands
1855
- // represented as an array of arguments to process
1856
- getCommands: function(commandName){
1857
- var commands = this._commands[commandName];
1858
-
1859
- // we don't have it, so add it
1860
- if (!commands){
1861
-
1862
- // build the configuration
1863
- commands = {
1864
- command: commandName,
1865
- instances: []
1866
- };
1867
-
1868
- // store it
1869
- this._commands[commandName] = commands;
1870
- }
1871
-
1872
- return commands;
1873
- },
1874
-
1875
- // Add a command by name, to the storage and store the
1876
- // args for the command
1877
- addCommand: function(commandName, args){
1878
- var command = this.getCommands(commandName);
1879
- command.instances.push(args);
1880
- },
1881
-
1882
- // Clear all commands for the given `commandName`
1883
- clearCommands: function(commandName){
1884
- var command = this.getCommands(commandName);
1885
- command.instances = [];
1886
- }
1887
- });
1888
-
1889
- return CommandStorage;
1890
- })();
1891
-
1892
- // Wreqr.Commands
1893
- // --------------
1894
- //
1895
- // A simple command pattern implementation. Register a command
1896
- // handler and execute it.
1897
- Wreqr.Commands = (function(Wreqr){
1898
- "use strict";
1899
-
1900
- return Wreqr.Handlers.extend({
1901
- // default storage type
1902
- storageType: Wreqr.CommandStorage,
1903
-
1904
- constructor: function(options){
1905
- this.options = options || {};
1906
-
1907
- this._initializeStorage(this.options);
1908
- this.on("handler:add", this._executeCommands, this);
1909
-
1910
- var args = Array.prototype.slice.call(arguments);
1911
- Wreqr.Handlers.prototype.constructor.apply(this, args);
1912
- },
1913
-
1914
- // Execute a named command with the supplied args
1915
- execute: function(name, args){
1916
- name = arguments[0];
1917
- args = Array.prototype.slice.call(arguments, 1);
1918
-
1919
- if (this.hasHandler(name)){
1920
- this.getHandler(name).apply(this, args);
1921
- } else {
1922
- this.storage.addCommand(name, args);
1923
- }
1924
-
1925
- },
1926
-
1927
- // Internal method to handle bulk execution of stored commands
1928
- _executeCommands: function(name, handler, context){
1929
- var command = this.storage.getCommands(name);
1930
-
1931
- // loop through and execute all the stored command instances
1932
- _.each(command.instances, function(args){
1933
- handler.apply(context, args);
1934
- });
1935
-
1936
- this.storage.clearCommands(name);
1937
- },
1938
-
1939
- // Internal method to initialize storage either from the type's
1940
- // `storageType` or the instance `options.storageType`.
1941
- _initializeStorage: function(options){
1942
- var storage;
1943
-
1944
- var StorageType = options.storageType || this.storageType;
1945
- if (_.isFunction(StorageType)){
1946
- storage = new StorageType();
1947
- } else {
1948
- storage = StorageType;
1949
- }
1950
-
1951
- this.storage = storage;
1952
- }
1953
- });
1954
-
1955
- })(Wreqr);
1956
-
1957
- // Wreqr.RequestResponse
1958
- // ---------------------
1959
- //
1960
- // A simple request/response implementation. Register a
1961
- // request handler, and return a response from it
1962
- Wreqr.RequestResponse = (function(Wreqr){
1963
- "use strict";
1964
-
1965
- return Wreqr.Handlers.extend({
1966
- request: function(){
1967
- var name = arguments[0];
1968
- var args = Array.prototype.slice.call(arguments, 1);
1969
-
1970
- return this.getHandler(name).apply(this, args);
1971
- }
1972
- });
1973
-
1974
- })(Wreqr);
1975
-
1976
- // Event Aggregator
1977
- // ----------------
1978
- // A pub-sub object that can be used to decouple various parts
1979
- // of an application through event-driven architecture.
1980
-
1981
- Wreqr.EventAggregator = (function(Backbone, _){
1982
- "use strict";
1983
- var EA = function(){};
1984
-
1985
- // Copy the `extend` function used by Backbone's classes
1986
- EA.extend = Backbone.Model.extend;
1987
-
1988
- // Copy the basic Backbone.Events on to the event aggregator
1989
- _.extend(EA.prototype, Backbone.Events);
1990
-
1991
- return EA;
1992
- })(Backbone, _);
1993
-
1994
-
1995
- return Wreqr;
1996
- })(Backbone, Backbone.Marionette, _);
1997
-
1998
- var Marionette = (function(global, Backbone, _){
1999
- "use strict";
2000
-
2001
- // Define and export the Marionette namespace
2002
- var Marionette = {};
2003
- Backbone.Marionette = Marionette;
2004
-
2005
- // Get the DOM manipulator for later use
2006
- Marionette.$ = Backbone.$;
2007
-
2008
- // Helpers
2009
- // -------
2010
-
2011
- // For slicing `arguments` in functions
2012
- var protoSlice = Array.prototype.slice;
2013
- function slice(args) {
2014
- return protoSlice.call(args);
2015
- }
2016
-
2017
- function throwError(message, name) {
2018
- var error = new Error(message);
2019
- error.name = name || 'Error';
2020
- throw error;
2021
- }
2022
-
2023
- // Marionette.extend
2024
- // -----------------
2025
-
2026
- // Borrow the Backbone `extend` method so we can use it as needed
2027
- Marionette.extend = Backbone.Model.extend;
2028
-
2029
- // Marionette.getOption
2030
- // --------------------
2031
-
2032
- // Retrieve an object, function or other value from a target
2033
- // object or its `options`, with `options` taking precedence.
2034
- Marionette.getOption = function(target, optionName){
2035
- if (!target || !optionName){ return; }
2036
- var value;
2037
-
2038
- if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
2039
- value = target.options[optionName];
2040
- } else {
2041
- value = target[optionName];
2042
- }
2043
-
2044
- return value;
2045
- };
2046
-
2047
- // Trigger an event and a corresponding method name. Examples:
2048
- //
2049
- // `this.triggerMethod("foo")` will trigger the "foo" event and
2050
- // call the "onFoo" method.
2051
- //
2052
- // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
2053
- // call the "onFooBar" method.
2054
- Marionette.triggerMethod = (function(){
2055
-
2056
- // split the event name on the :
2057
- var splitter = /(^|:)(\w)/gi;
2058
-
2059
- // take the event section ("section1:section2:section3")
2060
- // and turn it in to uppercase name
2061
- function getEventName(match, prefix, eventName) {
2062
- return eventName.toUpperCase();
2063
- }
2064
-
2065
- // actual triggerMethod name
2066
- var triggerMethod = function(event) {
2067
- // get the method name from the event name
2068
- var methodName = 'on' + event.replace(splitter, getEventName);
2069
- var method = this[methodName];
2070
-
2071
- // trigger the event
2072
- this.trigger.apply(this, arguments);
2073
-
2074
- // call the onMethodName if it exists
2075
- if (_.isFunction(method)) {
2076
- // pass all arguments, except the event name
2077
- return method.apply(this, _.tail(arguments));
2078
- }
2079
- };
2080
-
2081
- return triggerMethod;
2082
- })();
2083
-
2084
- // DOMRefresh
2085
- // ----------
2086
- //
2087
- // Monitor a view's state, and after it has been rendered and shown
2088
- // in the DOM, trigger a "dom:refresh" event every time it is
2089
- // re-rendered.
2090
-
2091
- Marionette.MonitorDOMRefresh = (function(){
2092
- // track when the view has been rendered
2093
- function handleShow(view){
2094
- view._isShown = true;
2095
- triggerDOMRefresh(view);
2096
- }
2097
-
2098
- // track when the view has been shown in the DOM,
2099
- // using a Marionette.Region (or by other means of triggering "show")
2100
- function handleRender(view){
2101
- view._isRendered = true;
2102
- triggerDOMRefresh(view);
2103
- }
2104
-
2105
- // Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
2106
- function triggerDOMRefresh(view){
2107
- if (view._isShown && view._isRendered){
2108
- if (_.isFunction(view.triggerMethod)){
2109
- view.triggerMethod("dom:refresh");
2110
- }
2111
- }
2112
- }
2113
-
2114
- // Export public API
2115
- return function(view){
2116
- view.listenTo(view, "show", function(){
2117
- handleShow(view);
2118
- });
2119
-
2120
- view.listenTo(view, "render", function(){
2121
- handleRender(view);
2122
- });
2123
- };
2124
- })();
2125
-
2126
-
2127
- // Marionette.bindEntityEvents & unbindEntityEvents
2128
- // ---------------------------
2129
- //
2130
- // These methods are used to bind/unbind a backbone "entity" (collection/model)
2131
- // to methods on a target object.
2132
- //
2133
- // The first parameter, `target`, must have a `listenTo` method from the
2134
- // EventBinder object.
2135
- //
2136
- // The second parameter is the entity (Backbone.Model or Backbone.Collection)
2137
- // to bind the events from.
2138
- //
2139
- // The third parameter is a hash of { "event:name": "eventHandler" }
2140
- // configuration. Multiple handlers can be separated by a space. A
2141
- // function can be supplied instead of a string handler name.
2142
-
2143
- (function(Marionette){
2144
- "use strict";
2145
-
2146
- // Bind the event to handlers specified as a string of
2147
- // handler names on the target object
2148
- function bindFromStrings(target, entity, evt, methods){
2149
- var methodNames = methods.split(/\s+/);
2150
-
2151
- _.each(methodNames,function(methodName) {
2152
-
2153
- var method = target[methodName];
2154
- if(!method) {
2155
- throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
2156
- }
2157
-
2158
- target.listenTo(entity, evt, method, target);
2159
- });
2160
- }
2161
-
2162
- // Bind the event to a supplied callback function
2163
- function bindToFunction(target, entity, evt, method){
2164
- target.listenTo(entity, evt, method, target);
2165
- }
2166
-
2167
- // Bind the event to handlers specified as a string of
2168
- // handler names on the target object
2169
- function unbindFromStrings(target, entity, evt, methods){
2170
- var methodNames = methods.split(/\s+/);
2171
-
2172
- _.each(methodNames,function(methodName) {
2173
- var method = target[methodName];
2174
- target.stopListening(entity, evt, method, target);
2175
- });
2176
- }
2177
-
2178
- // Bind the event to a supplied callback function
2179
- function unbindToFunction(target, entity, evt, method){
2180
- target.stopListening(entity, evt, method, target);
2181
- }
2182
-
2183
-
2184
- // generic looping function
2185
- function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
2186
- if (!entity || !bindings) { return; }
2187
-
2188
- // allow the bindings to be a function
2189
- if (_.isFunction(bindings)){
2190
- bindings = bindings.call(target);
2191
- }
2192
-
2193
- // iterate the bindings and bind them
2194
- _.each(bindings, function(methods, evt){
2195
-
2196
- // allow for a function as the handler,
2197
- // or a list of event names as a string
2198
- if (_.isFunction(methods)){
2199
- functionCallback(target, entity, evt, methods);
2200
- } else {
2201
- stringCallback(target, entity, evt, methods);
2202
- }
2203
-
2204
- });
2205
- }
2206
-
2207
- // Export Public API
2208
- Marionette.bindEntityEvents = function(target, entity, bindings){
2209
- iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
2210
- };
2211
-
2212
- Marionette.unbindEntityEvents = function(target, entity, bindings){
2213
- iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
2214
- };
2215
-
2216
- })(Marionette);
2217
-
2218
-
2219
- // Callbacks
2220
- // ---------
2221
-
2222
- // A simple way of managing a collection of callbacks
2223
- // and executing them at a later point in time, using jQuery's
2224
- // `Deferred` object.
2225
- Marionette.Callbacks = function(){
2226
- this._deferred = Marionette.$.Deferred();
2227
- this._callbacks = [];
2228
- };
2229
-
2230
- _.extend(Marionette.Callbacks.prototype, {
2231
-
2232
- // Add a callback to be executed. Callbacks added here are
2233
- // guaranteed to execute, even if they are added after the
2234
- // `run` method is called.
2235
- add: function(callback, contextOverride){
2236
- this._callbacks.push({cb: callback, ctx: contextOverride});
2237
-
2238
- this._deferred.done(function(context, options){
2239
- if (contextOverride){ context = contextOverride; }
2240
- callback.call(context, options);
2241
- });
2242
- },
2243
-
2244
- // Run all registered callbacks with the context specified.
2245
- // Additional callbacks can be added after this has been run
2246
- // and they will still be executed.
2247
- run: function(options, context){
2248
- this._deferred.resolve(context, options);
2249
- },
2250
-
2251
- // Resets the list of callbacks to be run, allowing the same list
2252
- // to be run multiple times - whenever the `run` method is called.
2253
- reset: function(){
2254
- var callbacks = this._callbacks;
2255
- this._deferred = Marionette.$.Deferred();
2256
- this._callbacks = [];
2257
-
2258
- _.each(callbacks, function(cb){
2259
- this.add(cb.cb, cb.ctx);
2260
- }, this);
2261
- }
2262
- });
2263
-
2264
-
2265
- // Marionette Controller
2266
- // ---------------------
2267
- //
2268
- // A multi-purpose object to use as a controller for
2269
- // modules and routers, and as a mediator for workflow
2270
- // and coordination of other objects, views, and more.
2271
- Marionette.Controller = function(options){
2272
- this.triggerMethod = Marionette.triggerMethod;
2273
- this.options = options || {};
2274
-
2275
- if (_.isFunction(this.initialize)){
2276
- this.initialize(this.options);
2277
- }
2278
- };
2279
-
2280
- Marionette.Controller.extend = Marionette.extend;
2281
-
2282
- // Controller Methods
2283
- // --------------
2284
-
2285
- // Ensure it can trigger events with Backbone.Events
2286
- _.extend(Marionette.Controller.prototype, Backbone.Events, {
2287
- close: function(){
2288
- this.stopListening();
2289
- this.triggerMethod("close");
2290
- this.unbind();
2291
- }
2292
- });
2293
-
2294
- // Region
2295
- // ------
2296
- //
2297
- // Manage the visual regions of your composite application. See
2298
- // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
2299
-
2300
- Marionette.Region = function(options){
2301
- this.options = options || {};
2302
-
2303
- this.el = Marionette.getOption(this, "el");
2304
-
2305
- if (!this.el){
2306
- var err = new Error("An 'el' must be specified for a region.");
2307
- err.name = "NoElError";
2308
- throw err;
2309
- }
2310
-
2311
- if (this.initialize){
2312
- var args = Array.prototype.slice.apply(arguments);
2313
- this.initialize.apply(this, args);
2314
- }
2315
- };
2316
-
2317
-
2318
- // Region Type methods
2319
- // -------------------
2320
-
2321
- _.extend(Marionette.Region, {
2322
-
2323
- // Build an instance of a region by passing in a configuration object
2324
- // and a default region type to use if none is specified in the config.
2325
- //
2326
- // The config object should either be a string as a jQuery DOM selector,
2327
- // a Region type directly, or an object literal that specifies both
2328
- // a selector and regionType:
2329
- //
2330
- // ```js
2331
- // {
2332
- // selector: "#foo",
2333
- // regionType: MyCustomRegion
2334
- // }
2335
- // ```
2336
- //
2337
- buildRegion: function(regionConfig, defaultRegionType){
2338
- var regionIsString = (typeof regionConfig === "string");
2339
- var regionSelectorIsString = (typeof regionConfig.selector === "string");
2340
- var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
2341
- var regionIsType = (typeof regionConfig === "function");
2342
-
2343
- if (!regionIsType && !regionIsString && !regionSelectorIsString) {
2344
- throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
2345
- }
2346
-
2347
- var selector, RegionType;
2348
-
2349
- // get the selector for the region
2350
-
2351
- if (regionIsString) {
2352
- selector = regionConfig;
2353
- }
2354
-
2355
- if (regionConfig.selector) {
2356
- selector = regionConfig.selector;
2357
- }
2358
-
2359
- // get the type for the region
2360
-
2361
- if (regionIsType){
2362
- RegionType = regionConfig;
2363
- }
2364
-
2365
- if (!regionIsType && regionTypeIsUndefined) {
2366
- RegionType = defaultRegionType;
2367
- }
2368
-
2369
- if (regionConfig.regionType) {
2370
- RegionType = regionConfig.regionType;
2371
- }
2372
-
2373
- // build the region instance
2374
- var region = new RegionType({
2375
- el: selector
2376
- });
2377
-
2378
- // override the `getEl` function if we have a parentEl
2379
- // this must be overridden to ensure the selector is found
2380
- // on the first use of the region. if we try to assign the
2381
- // region's `el` to `parentEl.find(selector)` in the object
2382
- // literal to build the region, the element will not be
2383
- // guaranteed to be in the DOM already, and will cause problems
2384
- if (regionConfig.parentEl){
2385
-
2386
- region.getEl = function(selector) {
2387
- var parentEl = regionConfig.parentEl;
2388
- if (_.isFunction(parentEl)){
2389
- parentEl = parentEl();
2390
- }
2391
- return parentEl.find(selector);
2392
- };
2393
- }
2394
-
2395
- return region;
2396
- }
2397
-
2398
- });
2399
-
2400
- // Region Instance Methods
2401
- // -----------------------
2402
-
2403
- _.extend(Marionette.Region.prototype, Backbone.Events, {
2404
-
2405
- // Displays a backbone view instance inside of the region.
2406
- // Handles calling the `render` method for you. Reads content
2407
- // directly from the `el` attribute. Also calls an optional
2408
- // `onShow` and `close` method on your view, just after showing
2409
- // or just before closing the view, respectively.
2410
- show: function(view){
2411
-
2412
- this.ensureEl();
2413
-
2414
- var isViewClosed = view.isClosed || _.isUndefined(view.$el);
2415
-
2416
- var isDifferentView = view !== this.currentView;
2417
-
2418
- if (isDifferentView) {
2419
- this.close();
2420
- }
2421
-
2422
- view.render();
2423
-
2424
- if (isDifferentView || isViewClosed) {
2425
- this.open(view);
2426
- }
2427
-
2428
- this.currentView = view;
2429
-
2430
- Marionette.triggerMethod.call(this, "show", view);
2431
- Marionette.triggerMethod.call(view, "show");
2432
- },
2433
-
2434
- ensureEl: function(){
2435
- if (!this.$el || this.$el.length === 0){
2436
- this.$el = this.getEl(this.el);
2437
- }
2438
- },
2439
-
2440
- // Override this method to change how the region finds the
2441
- // DOM element that it manages. Return a jQuery selector object.
2442
- getEl: function(selector){
2443
- return Marionette.$(selector);
2444
- },
2445
-
2446
- // Override this method to change how the new view is
2447
- // appended to the `$el` that the region is managing
2448
- open: function(view){
2449
- this.$el.empty().append(view.el);
2450
- },
2451
-
2452
- // Close the current view, if there is one. If there is no
2453
- // current view, it does nothing and returns immediately.
2454
- close: function(){
2455
- var view = this.currentView;
2456
- if (!view || view.isClosed){ return; }
2457
-
2458
- // call 'close' or 'remove', depending on which is found
2459
- if (view.close) { view.close(); }
2460
- else if (view.remove) { view.remove(); }
2461
-
2462
- Marionette.triggerMethod.call(this, "close");
2463
-
2464
- delete this.currentView;
2465
- },
2466
-
2467
- // Attach an existing view to the region. This
2468
- // will not call `render` or `onShow` for the new view,
2469
- // and will not replace the current HTML for the `el`
2470
- // of the region.
2471
- attachView: function(view){
2472
- this.currentView = view;
2473
- },
2474
-
2475
- // Reset the region by closing any existing view and
2476
- // clearing out the cached `$el`. The next time a view
2477
- // is shown via this region, the region will re-query the
2478
- // DOM for the region's `el`.
2479
- reset: function(){
2480
- this.close();
2481
- delete this.$el;
2482
- }
2483
- });
2484
-
2485
- // Copy the `extend` function used by Backbone's classes
2486
- Marionette.Region.extend = Marionette.extend;
2487
-
2488
- // Marionette.RegionManager
2489
- // ------------------------
2490
- //
2491
- // Manage one or more related `Marionette.Region` objects.
2492
- Marionette.RegionManager = (function(Marionette){
2493
-
2494
- var RegionManager = Marionette.Controller.extend({
2495
- constructor: function(options){
2496
- this._regions = {};
2497
- Marionette.Controller.prototype.constructor.call(this, options);
2498
- },
2499
-
2500
- // Add multiple regions using an object literal, where
2501
- // each key becomes the region name, and each value is
2502
- // the region definition.
2503
- addRegions: function(regionDefinitions, defaults){
2504
- var regions = {};
2505
-
2506
- _.each(regionDefinitions, function(definition, name){
2507
- if (typeof definition === "string"){
2508
- definition = { selector: definition };
2509
- }
2510
-
2511
- if (definition.selector){
2512
- definition = _.defaults({}, definition, defaults);
2513
- }
2514
-
2515
- var region = this.addRegion(name, definition);
2516
- regions[name] = region;
2517
- }, this);
2518
-
2519
- return regions;
2520
- },
2521
-
2522
- // Add an individual region to the region manager,
2523
- // and return the region instance
2524
- addRegion: function(name, definition){
2525
- var region;
2526
-
2527
- var isObject = _.isObject(definition);
2528
- var isString = _.isString(definition);
2529
- var hasSelector = !!definition.selector;
2530
-
2531
- if (isString || (isObject && hasSelector)){
2532
- region = Marionette.Region.buildRegion(definition, Marionette.Region);
2533
- } else if (_.isFunction(definition)){
2534
- region = Marionette.Region.buildRegion(definition, Marionette.Region);
2535
- } else {
2536
- region = definition;
2537
- }
2538
-
2539
- this._store(name, region);
2540
- this.triggerMethod("region:add", name, region);
2541
- return region;
2542
- },
2543
-
2544
- // Get a region by name
2545
- get: function(name){
2546
- return this._regions[name];
2547
- },
2548
-
2549
- // Remove a region by name
2550
- removeRegion: function(name){
2551
- var region = this._regions[name];
2552
- this._remove(name, region);
2553
- },
2554
-
2555
- // Close all regions in the region manager, and
2556
- // remove them
2557
- removeRegions: function(){
2558
- _.each(this._regions, function(region, name){
2559
- this._remove(name, region);
2560
- }, this);
2561
- },
2562
-
2563
- // Close all regions in the region manager, but
2564
- // leave them attached
2565
- closeRegions: function(){
2566
- _.each(this._regions, function(region, name){
2567
- region.close();
2568
- }, this);
2569
- },
2570
-
2571
- // Close all regions and shut down the region
2572
- // manager entirely
2573
- close: function(){
2574
- this.removeRegions();
2575
- var args = Array.prototype.slice.call(arguments);
2576
- Marionette.Controller.prototype.close.apply(this, args);
2577
- },
2578
-
2579
- // internal method to store regions
2580
- _store: function(name, region){
2581
- this._regions[name] = region;
2582
- this._setLength();
2583
- },
2584
-
2585
- // internal method to remove a region
2586
- _remove: function(name, region){
2587
- region.close();
2588
- delete this._regions[name];
2589
- this._setLength();
2590
- this.triggerMethod("region:remove", name, region);
2591
- },
2592
-
2593
- // set the number of regions current held
2594
- _setLength: function(){
2595
- this.length = _.size(this._regions);
2596
- }
2597
-
2598
- });
2599
-
2600
- // Borrowing this code from Backbone.Collection:
2601
- // http://backbonejs.org/docs/backbone.html#section-106
2602
- //
2603
- // Mix in methods from Underscore, for iteration, and other
2604
- // collection related features.
2605
- var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
2606
- 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
2607
- 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
2608
- 'last', 'without', 'isEmpty', 'pluck'];
2609
-
2610
- _.each(methods, function(method) {
2611
- RegionManager.prototype[method] = function() {
2612
- var regions = _.values(this._regions);
2613
- var args = [regions].concat(_.toArray(arguments));
2614
- return _[method].apply(_, args);
2615
- };
2616
- });
2617
-
2618
- return RegionManager;
2619
- })(Marionette);
2620
-
2621
-
2622
- // Template Cache
2623
- // --------------
2624
-
2625
- // Manage templates stored in `<script>` blocks,
2626
- // caching them for faster access.
2627
- Marionette.TemplateCache = function(templateId){
2628
- this.templateId = templateId;
2629
- };
2630
-
2631
- // TemplateCache object-level methods. Manage the template
2632
- // caches from these method calls instead of creating
2633
- // your own TemplateCache instances
2634
- _.extend(Marionette.TemplateCache, {
2635
- templateCaches: {},
2636
-
2637
- // Get the specified template by id. Either
2638
- // retrieves the cached version, or loads it
2639
- // from the DOM.
2640
- get: function(templateId){
2641
- var cachedTemplate = this.templateCaches[templateId];
2642
-
2643
- if (!cachedTemplate){
2644
- cachedTemplate = new Marionette.TemplateCache(templateId);
2645
- this.templateCaches[templateId] = cachedTemplate;
2646
- }
2647
-
2648
- return cachedTemplate.load();
2649
- },
2650
-
2651
- // Clear templates from the cache. If no arguments
2652
- // are specified, clears all templates:
2653
- // `clear()`
2654
- //
2655
- // If arguments are specified, clears each of the
2656
- // specified templates from the cache:
2657
- // `clear("#t1", "#t2", "...")`
2658
- clear: function(){
2659
- var i;
2660
- var args = slice(arguments);
2661
- var length = args.length;
2662
-
2663
- if (length > 0){
2664
- for(i=0; i<length; i++){
2665
- delete this.templateCaches[args[i]];
2666
- }
2667
- } else {
2668
- this.templateCaches = {};
2669
- }
2670
- }
2671
- });
2672
-
2673
- // TemplateCache instance methods, allowing each
2674
- // template cache object to manage its own state
2675
- // and know whether or not it has been loaded
2676
- _.extend(Marionette.TemplateCache.prototype, {
2677
-
2678
- // Internal method to load the template
2679
- load: function(){
2680
- // Guard clause to prevent loading this template more than once
2681
- if (this.compiledTemplate){
2682
- return this.compiledTemplate;
2683
- }
2684
-
2685
- // Load the template and compile it
2686
- var template = this.loadTemplate(this.templateId);
2687
- this.compiledTemplate = this.compileTemplate(template);
2688
-
2689
- return this.compiledTemplate;
2690
- },
2691
-
2692
- // Load a template from the DOM, by default. Override
2693
- // this method to provide your own template retrieval
2694
- // For asynchronous loading with AMD/RequireJS, consider
2695
- // using a template-loader plugin as described here:
2696
- // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
2697
- loadTemplate: function(templateId){
2698
- var template = Marionette.$(templateId).html();
2699
-
2700
- if (!template || template.length === 0){
2701
- throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
2702
- }
2703
-
2704
- return template;
2705
- },
2706
-
2707
- // Pre-compile the template before caching it. Override
2708
- // this method if you do not need to pre-compile a template
2709
- // (JST / RequireJS for example) or if you want to change
2710
- // the template engine used (Handebars, etc).
2711
- compileTemplate: function(rawTemplate){
2712
- return _.template(rawTemplate);
2713
- }
2714
- });
2715
-
2716
-
2717
- // Renderer
2718
- // --------
2719
-
2720
- // Render a template with data by passing in the template
2721
- // selector and the data to render.
2722
- Marionette.Renderer = {
2723
-
2724
- // Render a template with data. The `template` parameter is
2725
- // passed to the `TemplateCache` object to retrieve the
2726
- // template function. Override this method to provide your own
2727
- // custom rendering and template handling for all of Marionette.
2728
- render: function(template, data){
2729
-
2730
- if (!template) {
2731
- var error = new Error("Cannot render the template since it's false, null or undefined.");
2732
- error.name = "TemplateNotFoundError";
2733
- throw error;
2734
- }
2735
-
2736
- var templateFunc;
2737
- if (typeof template === "function"){
2738
- templateFunc = template;
2739
- } else {
2740
- templateFunc = Marionette.TemplateCache.get(template);
2741
- }
2742
-
2743
- return templateFunc(data);
2744
- }
2745
- };
2746
-
2747
-
2748
-
2749
- // Marionette.View
2750
- // ---------------
2751
-
2752
- // The core view type that other Marionette views extend from.
2753
- Marionette.View = Backbone.View.extend({
2754
-
2755
- constructor: function(){
2756
- _.bindAll(this, "render");
2757
-
2758
- var args = Array.prototype.slice.apply(arguments);
2759
- Backbone.View.prototype.constructor.apply(this, args);
2760
-
2761
- Marionette.MonitorDOMRefresh(this);
2762
- this.listenTo(this, "show", this.onShowCalled, this);
2763
- },
2764
-
2765
- // import the "triggerMethod" to trigger events with corresponding
2766
- // methods if the method exists
2767
- triggerMethod: Marionette.triggerMethod,
2768
-
2769
- // Get the template for this view
2770
- // instance. You can set a `template` attribute in the view
2771
- // definition or pass a `template: "whatever"` parameter in
2772
- // to the constructor options.
2773
- getTemplate: function(){
2774
- return Marionette.getOption(this, "template");
2775
- },
2776
-
2777
- // Mix in template helper methods. Looks for a
2778
- // `templateHelpers` attribute, which can either be an
2779
- // object literal, or a function that returns an object
2780
- // literal. All methods and attributes from this object
2781
- // are copies to the object passed in.
2782
- mixinTemplateHelpers: function(target){
2783
- target = target || {};
2784
- var templateHelpers = this.templateHelpers;
2785
- if (_.isFunction(templateHelpers)){
2786
- templateHelpers = templateHelpers.call(this);
2787
- }
2788
- return _.extend(target, templateHelpers);
2789
- },
2790
-
2791
- // Configure `triggers` to forward DOM events to view
2792
- // events. `triggers: {"click .foo": "do:foo"}`
2793
- configureTriggers: function(){
2794
- if (!this.triggers) { return; }
2795
-
2796
- var triggerEvents = {};
2797
-
2798
- // Allow `triggers` to be configured as a function
2799
- var triggers = _.result(this, "triggers");
2800
-
2801
- // Configure the triggers, prevent default
2802
- // action and stop propagation of DOM events
2803
- _.each(triggers, function(value, key){
2804
-
2805
- // build the event handler function for the DOM event
2806
- triggerEvents[key] = function(e){
2807
-
2808
- // stop the event in its tracks
2809
- if (e && e.preventDefault){ e.preventDefault(); }
2810
- if (e && e.stopPropagation){ e.stopPropagation(); }
2811
-
2812
- // build the args for the event
2813
- var args = {
2814
- view: this,
2815
- model: this.model,
2816
- collection: this.collection
2817
- };
2818
-
2819
- // trigger the event
2820
- this.triggerMethod(value, args);
2821
- };
2822
-
2823
- }, this);
2824
-
2825
- return triggerEvents;
2826
- },
2827
-
2828
- // Overriding Backbone.View's delegateEvents to handle
2829
- // the `triggers`, `modelEvents`, and `collectionEvents` configuration
2830
- delegateEvents: function(events){
2831
- this._delegateDOMEvents(events);
2832
- Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
2833
- Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
2834
- },
2835
-
2836
- // internal method to delegate DOM events and triggers
2837
- _delegateDOMEvents: function(events){
2838
- events = events || this.events;
2839
- if (_.isFunction(events)){ events = events.call(this); }
2840
-
2841
- var combinedEvents = {};
2842
- var triggers = this.configureTriggers();
2843
- _.extend(combinedEvents, events, triggers);
2844
-
2845
- Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
2846
- },
2847
-
2848
- // Overriding Backbone.View's undelegateEvents to handle unbinding
2849
- // the `triggers`, `modelEvents`, and `collectionEvents` config
2850
- undelegateEvents: function(){
2851
- var args = Array.prototype.slice.call(arguments);
2852
- Backbone.View.prototype.undelegateEvents.apply(this, args);
2853
-
2854
- Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
2855
- Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
2856
- },
2857
-
2858
- // Internal method, handles the `show` event.
2859
- onShowCalled: function(){},
2860
-
2861
- // Default `close` implementation, for removing a view from the
2862
- // DOM and unbinding it. Regions will call this method
2863
- // for you. You can specify an `onClose` method in your view to
2864
- // add custom code that is called after the view is closed.
2865
- close: function(){
2866
- if (this.isClosed) { return; }
2867
-
2868
- // allow the close to be stopped by returning `false`
2869
- // from the `onBeforeClose` method
2870
- var shouldClose = this.triggerMethod("before:close");
2871
- if (shouldClose === false){
2872
- return;
2873
- }
2874
-
2875
- // mark as closed before doing the actual close, to
2876
- // prevent infinite loops within "close" event handlers
2877
- // that are trying to close other views
2878
- this.isClosed = true;
2879
- this.triggerMethod("close");
2880
-
2881
- // unbind UI elements
2882
- this.unbindUIElements();
2883
-
2884
- // remove the view from the DOM
2885
- this.remove();
2886
- },
2887
-
2888
- // This method binds the elements specified in the "ui" hash inside the view's code with
2889
- // the associated jQuery selectors.
2890
- bindUIElements: function(){
2891
- if (!this.ui) { return; }
2892
-
2893
- // store the ui hash in _uiBindings so they can be reset later
2894
- // and so re-rendering the view will be able to find the bindings
2895
- if (!this._uiBindings){
2896
- this._uiBindings = this.ui;
2897
- }
2898
-
2899
- // get the bindings result, as a function or otherwise
2900
- var bindings = _.result(this, "_uiBindings");
2901
-
2902
- // empty the ui so we don't have anything to start with
2903
- this.ui = {};
2904
-
2905
- // bind each of the selectors
2906
- _.each(_.keys(bindings), function(key) {
2907
- var selector = bindings[key];
2908
- this.ui[key] = this.$(selector);
2909
- }, this);
2910
- },
2911
-
2912
- // This method unbinds the elements specified in the "ui" hash
2913
- unbindUIElements: function(){
2914
- if (!this.ui){ return; }
2915
-
2916
- // delete all of the existing ui bindings
2917
- _.each(this.ui, function($el, name){
2918
- delete this.ui[name];
2919
- }, this);
2920
-
2921
- // reset the ui element to the original bindings configuration
2922
- this.ui = this._uiBindings;
2923
- delete this._uiBindings;
2924
- }
2925
- });
2926
-
2927
- // Item View
2928
- // ---------
2929
-
2930
- // A single item view implementation that contains code for rendering
2931
- // with underscore.js templates, serializing the view's model or collection,
2932
- // and calling several methods on extended views, such as `onRender`.
2933
- Marionette.ItemView = Marionette.View.extend({
2934
-
2935
- // Setting up the inheritance chain which allows changes to
2936
- // Marionette.View.prototype.constructor which allows overriding
2937
- constructor: function(){
2938
- Marionette.View.prototype.constructor.apply(this, slice(arguments));
2939
- },
2940
-
2941
- // Serialize the model or collection for the view. If a model is
2942
- // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
2943
- // is also called, but is used to populate an `items` array in the
2944
- // resulting data. If both are found, defaults to the model.
2945
- // You can override the `serializeData` method in your own view
2946
- // definition, to provide custom serialization for your view's data.
2947
- serializeData: function(){
2948
- var data = {};
2949
-
2950
- if (this.model) {
2951
- data = this.model.toJSON();
2952
- }
2953
- else if (this.collection) {
2954
- data = { items: this.collection.toJSON() };
2955
- }
2956
-
2957
- return data;
2958
- },
2959
-
2960
- // Render the view, defaulting to underscore.js templates.
2961
- // You can override this in your view definition to provide
2962
- // a very specific rendering for your view. In general, though,
2963
- // you should override the `Marionette.Renderer` object to
2964
- // change how Marionette renders views.
2965
- render: function(){
2966
- this.isClosed = false;
2967
-
2968
- this.triggerMethod("before:render", this);
2969
- this.triggerMethod("item:before:render", this);
2970
-
2971
- var data = this.serializeData();
2972
- data = this.mixinTemplateHelpers(data);
2973
-
2974
- var template = this.getTemplate();
2975
- var html = Marionette.Renderer.render(template, data);
2976
-
2977
- this.$el.html(html);
2978
- this.bindUIElements();
2979
-
2980
- this.triggerMethod("render", this);
2981
- this.triggerMethod("item:rendered", this);
2982
-
2983
- return this;
2984
- },
2985
-
2986
- // Override the default close event to add a few
2987
- // more events that are triggered.
2988
- close: function(){
2989
- if (this.isClosed){ return; }
2990
-
2991
- this.triggerMethod('item:before:close');
2992
-
2993
- Marionette.View.prototype.close.apply(this, slice(arguments));
2994
-
2995
- this.triggerMethod('item:closed');
2996
- }
2997
- });
2998
-
2999
- // Collection View
3000
- // ---------------
3001
-
3002
- // A view that iterates over a Backbone.Collection
3003
- // and renders an individual ItemView for each model.
3004
- Marionette.CollectionView = Marionette.View.extend({
3005
- // used as the prefix for item view events
3006
- // that are forwarded through the collectionview
3007
- itemViewEventPrefix: "itemview",
3008
-
3009
- // constructor
3010
- constructor: function(options){
3011
- this._initChildViewStorage();
3012
-
3013
- Marionette.View.prototype.constructor.apply(this, slice(arguments));
3014
-
3015
- this._initialEvents();
3016
- },
3017
-
3018
- // Configured the initial events that the collection view
3019
- // binds to. Override this method to prevent the initial
3020
- // events, or to add your own initial events.
3021
- _initialEvents: function(){
3022
- if (this.collection){
3023
- this.listenTo(this.collection, "add", this.addChildView, this);
3024
- this.listenTo(this.collection, "remove", this.removeItemView, this);
3025
- this.listenTo(this.collection, "reset", this.render, this);
3026
- }
3027
- },
3028
-
3029
- // Handle a child item added to the collection
3030
- addChildView: function(item, collection, options){
3031
- this.closeEmptyView();
3032
- var ItemView = this.getItemView(item);
3033
- var index = this.collection.indexOf(item);
3034
- this.addItemView(item, ItemView, index);
3035
- },
3036
-
3037
- // Override from `Marionette.View` to guarantee the `onShow` method
3038
- // of child views is called.
3039
- onShowCalled: function(){
3040
- this.children.each(function(child){
3041
- Marionette.triggerMethod.call(child, "show");
3042
- });
3043
- },
3044
-
3045
- // Internal method to trigger the before render callbacks
3046
- // and events
3047
- triggerBeforeRender: function(){
3048
- this.triggerMethod("before:render", this);
3049
- this.triggerMethod("collection:before:render", this);
3050
- },
3051
-
3052
- // Internal method to trigger the rendered callbacks and
3053
- // events
3054
- triggerRendered: function(){
3055
- this.triggerMethod("render", this);
3056
- this.triggerMethod("collection:rendered", this);
3057
- },
3058
-
3059
- // Render the collection of items. Override this method to
3060
- // provide your own implementation of a render function for
3061
- // the collection view.
3062
- render: function(){
3063
- this.isClosed = false;
3064
- this.triggerBeforeRender();
3065
- this._renderChildren();
3066
- this.triggerRendered();
3067
- return this;
3068
- },
3069
-
3070
- // Internal method. Separated so that CompositeView can have
3071
- // more control over events being triggered, around the rendering
3072
- // process
3073
- _renderChildren: function(){
3074
- this.closeEmptyView();
3075
- this.closeChildren();
3076
-
3077
- if (this.collection && this.collection.length > 0) {
3078
- this.showCollection();
3079
- } else {
3080
- this.showEmptyView();
3081
- }
3082
- },
3083
-
3084
- // Internal method to loop through each item in the
3085
- // collection view and show it
3086
- showCollection: function(){
3087
- var ItemView;
3088
- this.collection.each(function(item, index){
3089
- ItemView = this.getItemView(item);
3090
- this.addItemView(item, ItemView, index);
3091
- }, this);
3092
- },
3093
-
3094
- // Internal method to show an empty view in place of
3095
- // a collection of item views, when the collection is
3096
- // empty
3097
- showEmptyView: function(){
3098
- var EmptyView = Marionette.getOption(this, "emptyView");
3099
-
3100
- if (EmptyView && !this._showingEmptyView){
3101
- this._showingEmptyView = true;
3102
- var model = new Backbone.Model();
3103
- this.addItemView(model, EmptyView, 0);
3104
- }
3105
- },
3106
-
3107
- // Internal method to close an existing emptyView instance
3108
- // if one exists. Called when a collection view has been
3109
- // rendered empty, and then an item is added to the collection.
3110
- closeEmptyView: function(){
3111
- if (this._showingEmptyView){
3112
- this.closeChildren();
3113
- delete this._showingEmptyView;
3114
- }
3115
- },
3116
-
3117
- // Retrieve the itemView type, either from `this.options.itemView`
3118
- // or from the `itemView` in the object definition. The "options"
3119
- // takes precedence.
3120
- getItemView: function(item){
3121
- var itemView = Marionette.getOption(this, "itemView");
3122
-
3123
- if (!itemView){
3124
- throwError("An `itemView` must be specified", "NoItemViewError");
3125
- }
3126
-
3127
- return itemView;
3128
- },
3129
-
3130
- // Render the child item's view and add it to the
3131
- // HTML for the collection view.
3132
- addItemView: function(item, ItemView, index){
3133
- // get the itemViewOptions if any were specified
3134
- var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
3135
- if (_.isFunction(itemViewOptions)){
3136
- itemViewOptions = itemViewOptions.call(this, item, index);
3137
- }
3138
-
3139
- // build the view
3140
- var view = this.buildItemView(item, ItemView, itemViewOptions);
3141
-
3142
- // set up the child view event forwarding
3143
- this.addChildViewEventForwarding(view);
3144
-
3145
- // this view is about to be added
3146
- this.triggerMethod("before:item:added", view);
3147
-
3148
- // Store the child view itself so we can properly
3149
- // remove and/or close it later
3150
- this.children.add(view);
3151
-
3152
- // Render it and show it
3153
- this.renderItemView(view, index);
3154
-
3155
- // call the "show" method if the collection view
3156
- // has already been shown
3157
- if (this._isShown){
3158
- Marionette.triggerMethod.call(view, "show");
3159
- }
3160
-
3161
- // this view was added
3162
- this.triggerMethod("after:item:added", view);
3163
- },
3164
-
3165
- // Set up the child view event forwarding. Uses an "itemview:"
3166
- // prefix in front of all forwarded events.
3167
- addChildViewEventForwarding: function(view){
3168
- var prefix = Marionette.getOption(this, "itemViewEventPrefix");
3169
-
3170
- // Forward all child item view events through the parent,
3171
- // prepending "itemview:" to the event name
3172
- this.listenTo(view, "all", function(){
3173
- var args = slice(arguments);
3174
- args[0] = prefix + ":" + args[0];
3175
- args.splice(1, 0, view);
3176
-
3177
- Marionette.triggerMethod.apply(this, args);
3178
- }, this);
3179
- },
3180
-
3181
- // render the item view
3182
- renderItemView: function(view, index) {
3183
- view.render();
3184
- this.appendHtml(this, view, index);
3185
- },
3186
-
3187
- // Build an `itemView` for every model in the collection.
3188
- buildItemView: function(item, ItemViewType, itemViewOptions){
3189
- var options = _.extend({model: item}, itemViewOptions);
3190
- return new ItemViewType(options);
3191
- },
3192
-
3193
- // get the child view by item it holds, and remove it
3194
- removeItemView: function(item){
3195
- var view = this.children.findByModel(item);
3196
- this.removeChildView(view);
3197
- this.checkEmpty();
3198
- },
3199
-
3200
- // Remove the child view and close it
3201
- removeChildView: function(view){
3202
-
3203
- // shut down the child view properly,
3204
- // including events that the collection has from it
3205
- if (view){
3206
- this.stopListening(view);
3207
-
3208
- // call 'close' or 'remove', depending on which is found
3209
- if (view.close) { view.close(); }
3210
- else if (view.remove) { view.remove(); }
3211
-
3212
- this.children.remove(view);
3213
- }
3214
-
3215
- this.triggerMethod("item:removed", view);
3216
- },
3217
-
3218
- // helper to show the empty view if the collection is empty
3219
- checkEmpty: function() {
3220
- // check if we're empty now, and if we are, show the
3221
- // empty view
3222
- if (!this.collection || this.collection.length === 0){
3223
- this.showEmptyView();
3224
- }
3225
- },
3226
-
3227
- // Append the HTML to the collection's `el`.
3228
- // Override this method to do something other
3229
- // then `.append`.
3230
- appendHtml: function(collectionView, itemView, index){
3231
- collectionView.$el.append(itemView.el);
3232
- },
3233
-
3234
- // Internal method to set up the `children` object for
3235
- // storing all of the child views
3236
- _initChildViewStorage: function(){
3237
- this.children = new Backbone.ChildViewContainer();
3238
- },
3239
-
3240
- // Handle cleanup and other closing needs for
3241
- // the collection of views.
3242
- close: function(){
3243
- if (this.isClosed){ return; }
3244
-
3245
- this.triggerMethod("collection:before:close");
3246
- this.closeChildren();
3247
- this.triggerMethod("collection:closed");
3248
-
3249
- Marionette.View.prototype.close.apply(this, slice(arguments));
3250
- },
3251
-
3252
- // Close the child views that this collection view
3253
- // is holding on to, if any
3254
- closeChildren: function(){
3255
- this.children.each(function(child){
3256
- this.removeChildView(child);
3257
- }, this);
3258
- this.checkEmpty();
3259
- }
3260
- });
3261
-
3262
-
3263
- // Composite View
3264
- // --------------
3265
-
3266
- // Used for rendering a branch-leaf, hierarchical structure.
3267
- // Extends directly from CollectionView and also renders an
3268
- // an item view as `modelView`, for the top leaf
3269
- Marionette.CompositeView = Marionette.CollectionView.extend({
3270
-
3271
- // Setting up the inheritance chain which allows changes to
3272
- // Marionette.CollectionView.prototype.constructor which allows overriding
3273
- constructor: function(){
3274
- Marionette.CollectionView.prototype.constructor.apply(this, slice(arguments));
3275
- },
3276
-
3277
- // Configured the initial events that the composite view
3278
- // binds to. Override this method to prevent the initial
3279
- // events, or to add your own initial events.
3280
- _initialEvents: function(){
3281
- if (this.collection){
3282
- this.listenTo(this.collection, "add", this.addChildView, this);
3283
- this.listenTo(this.collection, "remove", this.removeItemView, this);
3284
- this.listenTo(this.collection, "reset", this._renderChildren, this);
3285
- }
3286
- },
3287
-
3288
- // Retrieve the `itemView` to be used when rendering each of
3289
- // the items in the collection. The default is to return
3290
- // `this.itemView` or Marionette.CompositeView if no `itemView`
3291
- // has been defined
3292
- getItemView: function(item){
3293
- var itemView = Marionette.getOption(this, "itemView") || this.constructor;
3294
-
3295
- if (!itemView){
3296
- throwError("An `itemView` must be specified", "NoItemViewError");
3297
- }
3298
-
3299
- return itemView;
3300
- },
3301
-
3302
- // Serialize the collection for the view.
3303
- // You can override the `serializeData` method in your own view
3304
- // definition, to provide custom serialization for your view's data.
3305
- serializeData: function(){
3306
- var data = {};
3307
-
3308
- if (this.model){
3309
- data = this.model.toJSON();
3310
- }
3311
-
3312
- return data;
3313
- },
3314
-
3315
- // Renders the model once, and the collection once. Calling
3316
- // this again will tell the model's view to re-render itself
3317
- // but the collection will not re-render.
3318
- render: function(){
3319
- this.isRendered = true;
3320
- this.isClosed = false;
3321
- this.resetItemViewContainer();
3322
-
3323
- this.triggerBeforeRender();
3324
- var html = this.renderModel();
3325
- this.$el.html(html);
3326
- // the ui bindings is done here and not at the end of render since they
3327
- // will not be available until after the model is rendered, but should be
3328
- // available before the collection is rendered.
3329
- this.bindUIElements();
3330
- this.triggerMethod("composite:model:rendered");
3331
-
3332
- this._renderChildren();
3333
-
3334
- this.triggerMethod("composite:rendered");
3335
- this.triggerRendered();
3336
- return this;
3337
- },
3338
-
3339
- _renderChildren: function(){
3340
- if (this.isRendered){
3341
- Marionette.CollectionView.prototype._renderChildren.call(this);
3342
- this.triggerMethod("composite:collection:rendered");
3343
- }
3344
- },
3345
-
3346
- // Render an individual model, if we have one, as
3347
- // part of a composite view (branch / leaf). For example:
3348
- // a treeview.
3349
- renderModel: function(){
3350
- var data = {};
3351
- data = this.serializeData();
3352
- data = this.mixinTemplateHelpers(data);
3353
-
3354
- var template = this.getTemplate();
3355
- return Marionette.Renderer.render(template, data);
3356
- },
3357
-
3358
- // Appends the `el` of itemView instances to the specified
3359
- // `itemViewContainer` (a jQuery selector). Override this method to
3360
- // provide custom logic of how the child item view instances have their
3361
- // HTML appended to the composite view instance.
3362
- appendHtml: function(cv, iv, index){
3363
- var $container = this.getItemViewContainer(cv);
3364
- $container.append(iv.el);
3365
- },
3366
-
3367
- // Internal method to ensure an `$itemViewContainer` exists, for the
3368
- // `appendHtml` method to use.
3369
- getItemViewContainer: function(containerView){
3370
- if ("$itemViewContainer" in containerView){
3371
- return containerView.$itemViewContainer;
3372
- }
3373
-
3374
- var container;
3375
- if (containerView.itemViewContainer){
3376
-
3377
- var selector = _.result(containerView, "itemViewContainer");
3378
- container = containerView.$(selector);
3379
- if (container.length <= 0) {
3380
- throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
3381
- }
3382
-
3383
- } else {
3384
- container = containerView.$el;
3385
- }
3386
-
3387
- containerView.$itemViewContainer = container;
3388
- return container;
3389
- },
3390
-
3391
- // Internal method to reset the `$itemViewContainer` on render
3392
- resetItemViewContainer: function(){
3393
- if (this.$itemViewContainer){
3394
- delete this.$itemViewContainer;
3395
- }
3396
- }
3397
- });
3398
-
3399
-
3400
- // Layout
3401
- // ------
3402
-
3403
- // Used for managing application layouts, nested layouts and
3404
- // multiple regions within an application or sub-application.
3405
- //
3406
- // A specialized view type that renders an area of HTML and then
3407
- // attaches `Region` instances to the specified `regions`.
3408
- // Used for composite view management and sub-application areas.
3409
- Marionette.Layout = Marionette.ItemView.extend({
3410
- regionType: Marionette.Region,
3411
-
3412
- // Ensure the regions are available when the `initialize` method
3413
- // is called.
3414
- constructor: function (options) {
3415
- options = options || {};
3416
-
3417
- this._firstRender = true;
3418
- this._initializeRegions(options);
3419
-
3420
- Marionette.ItemView.prototype.constructor.call(this, options);
3421
- },
3422
-
3423
- // Layout's render will use the existing region objects the
3424
- // first time it is called. Subsequent calls will close the
3425
- // views that the regions are showing and then reset the `el`
3426
- // for the regions to the newly rendered DOM elements.
3427
- render: function(){
3428
-
3429
- if (this._firstRender){
3430
- // if this is the first render, don't do anything to
3431
- // reset the regions
3432
- this._firstRender = false;
3433
- } else if (this.isClosed){
3434
- // a previously closed layout means we need to
3435
- // completely re-initialize the regions
3436
- this._initializeRegions();
3437
- } else {
3438
- // If this is not the first render call, then we need to
3439
- // re-initializing the `el` for each region
3440
- this._reInitializeRegions();
3441
- }
3442
-
3443
- var args = Array.prototype.slice.apply(arguments);
3444
- var result = Marionette.ItemView.prototype.render.apply(this, args);
3445
-
3446
- return result;
3447
- },
3448
-
3449
- // Handle closing regions, and then close the view itself.
3450
- close: function () {
3451
- if (this.isClosed){ return; }
3452
- this.regionManager.close();
3453
- var args = Array.prototype.slice.apply(arguments);
3454
- Marionette.ItemView.prototype.close.apply(this, args);
3455
- },
3456
-
3457
- // Add a single region, by name, to the layout
3458
- addRegion: function(name, definition){
3459
- var regions = {};
3460
- regions[name] = definition;
3461
- return this.addRegions(regions)[name];
3462
- },
3463
-
3464
- // Add multiple regions as a {name: definition, name2: def2} object literal
3465
- addRegions: function(regions){
3466
- this.regions = _.extend(this.regions || {}, regions);
3467
- return this._buildRegions(regions);
3468
- },
3469
-
3470
- // Remove a single region from the Layout, by name
3471
- removeRegion: function(name){
3472
- return this.regionManager.removeRegion(name);
3473
- },
3474
-
3475
- // internal method to build regions
3476
- _buildRegions: function(regions){
3477
- var that = this;
3478
-
3479
- var defaults = {
3480
- parentEl: function(){ return that.$el; }
3481
- };
3482
-
3483
- return this.regionManager.addRegions(regions, defaults);
3484
- },
3485
-
3486
- // Internal method to initialize the regions that have been defined in a
3487
- // `regions` attribute on this layout.
3488
- _initializeRegions: function (options) {
3489
- var regions;
3490
- this._initRegionManager();
3491
-
3492
- if (_.isFunction(this.regions)) {
3493
- regions = this.regions(options);
3494
- } else {
3495
- regions = this.regions || {};
3496
- }
3497
-
3498
- this.addRegions(regions);
3499
- },
3500
-
3501
- // Internal method to re-initialize all of the regions by updating the `el` that
3502
- // they point to
3503
- _reInitializeRegions: function(){
3504
- this.regionManager.closeRegions();
3505
- this.regionManager.each(function(region){
3506
- region.reset();
3507
- });
3508
- },
3509
-
3510
- // Internal method to initialize the region manager
3511
- // and all regions in it
3512
- _initRegionManager: function(){
3513
- this.regionManager = new Marionette.RegionManager();
3514
-
3515
- this.listenTo(this.regionManager, "region:add", function(name, region){
3516
- this[name] = region;
3517
- this.trigger("region:add", name, region);
3518
- });
3519
-
3520
- this.listenTo(this.regionManager, "region:remove", function(name, region){
3521
- delete this[name];
3522
- this.trigger("region:remove", name, region);
3523
- });
3524
- }
3525
- });
3526
-
3527
-
3528
- // AppRouter
3529
- // ---------
3530
-
3531
- // Reduce the boilerplate code of handling route events
3532
- // and then calling a single method on another object.
3533
- // Have your routers configured to call the method on
3534
- // your object, directly.
3535
- //
3536
- // Configure an AppRouter with `appRoutes`.
3537
- //
3538
- // App routers can only take one `controller` object.
3539
- // It is recommended that you divide your controller
3540
- // objects in to smaller pieces of related functionality
3541
- // and have multiple routers / controllers, instead of
3542
- // just one giant router and controller.
3543
- //
3544
- // You can also add standard routes to an AppRouter.
3545
-
3546
- Marionette.AppRouter = Backbone.Router.extend({
3547
-
3548
- constructor: function(options){
3549
- Backbone.Router.prototype.constructor.apply(this, slice(arguments));
3550
-
3551
- this.options = options;
3552
-
3553
- if (this.appRoutes){
3554
- var controller = Marionette.getOption(this, "controller");
3555
- this.processAppRoutes(controller, this.appRoutes);
3556
- }
3557
- },
3558
-
3559
- // Internal method to process the `appRoutes` for the
3560
- // router, and turn them in to routes that trigger the
3561
- // specified method on the specified `controller`.
3562
- processAppRoutes: function(controller, appRoutes) {
3563
- var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
3564
-
3565
- _.each(routeNames, function(route) {
3566
- var methodName = appRoutes[route];
3567
- var method = controller[methodName];
3568
-
3569
- if (!method) {
3570
- throw new Error("Method '" + methodName + "' was not found on the controller");
3571
- }
3572
-
3573
- this.route(route, methodName, _.bind(method, controller));
3574
- }, this);
3575
- }
3576
- });
3577
-
3578
-
3579
- // Application
3580
- // -----------
3581
-
3582
- // Contain and manage the composite application as a whole.
3583
- // Stores and starts up `Region` objects, includes an
3584
- // event aggregator as `app.vent`
3585
- Marionette.Application = function(options){
3586
- this._initRegionManager();
3587
- this._initCallbacks = new Marionette.Callbacks();
3588
- this.vent = new Backbone.Wreqr.EventAggregator();
3589
- this.commands = new Backbone.Wreqr.Commands();
3590
- this.reqres = new Backbone.Wreqr.RequestResponse();
3591
- this.submodules = {};
3592
-
3593
- _.extend(this, options);
3594
-
3595
- this.triggerMethod = Marionette.triggerMethod;
3596
- };
3597
-
3598
- _.extend(Marionette.Application.prototype, Backbone.Events, {
3599
- // Command execution, facilitated by Backbone.Wreqr.Commands
3600
- execute: function(){
3601
- var args = Array.prototype.slice.apply(arguments);
3602
- this.commands.execute.apply(this.commands, args);
3603
- },
3604
-
3605
- // Request/response, facilitated by Backbone.Wreqr.RequestResponse
3606
- request: function(){
3607
- var args = Array.prototype.slice.apply(arguments);
3608
- return this.reqres.request.apply(this.reqres, args);
3609
- },
3610
-
3611
- // Add an initializer that is either run at when the `start`
3612
- // method is called, or run immediately if added after `start`
3613
- // has already been called.
3614
- addInitializer: function(initializer){
3615
- this._initCallbacks.add(initializer);
3616
- },
3617
-
3618
- // kick off all of the application's processes.
3619
- // initializes all of the regions that have been added
3620
- // to the app, and runs all of the initializer functions
3621
- start: function(options){
3622
- this.triggerMethod("initialize:before", options);
3623
- this._initCallbacks.run(options, this);
3624
- this.triggerMethod("initialize:after", options);
3625
-
3626
- this.triggerMethod("start", options);
3627
- },
3628
-
3629
- // Add regions to your app.
3630
- // Accepts a hash of named strings or Region objects
3631
- // addRegions({something: "#someRegion"})
3632
- // addRegions({something: Region.extend({el: "#someRegion"}) });
3633
- addRegions: function(regions){
3634
- return this._regionManager.addRegions(regions);
3635
- },
3636
-
3637
- // Removes a region from your app.
3638
- // Accepts the regions name
3639
- // removeRegion('myRegion')
3640
- removeRegion: function(region) {
3641
- this._regionManager.removeRegion(region);
3642
- },
3643
-
3644
- // Create a module, attached to the application
3645
- module: function(moduleNames, moduleDefinition){
3646
- // slice the args, and add this application object as the
3647
- // first argument of the array
3648
- var args = slice(arguments);
3649
- args.unshift(this);
3650
-
3651
- // see the Marionette.Module object for more information
3652
- return Marionette.Module.create.apply(Marionette.Module, args);
3653
- },
3654
-
3655
- // Internal method to set up the region manager
3656
- _initRegionManager: function(){
3657
- this._regionManager = new Marionette.RegionManager();
3658
-
3659
- this.listenTo(this._regionManager, "region:add", function(name, region){
3660
- this[name] = region;
3661
- });
3662
-
3663
- this.listenTo(this._regionManager, "region:remove", function(name, region){
3664
- delete this[name];
3665
- });
3666
- }
3667
- });
3668
-
3669
- // Copy the `extend` function used by Backbone's classes
3670
- Marionette.Application.extend = Marionette.extend;
3671
-
3672
- // Module
3673
- // ------
3674
-
3675
- // A simple module system, used to create privacy and encapsulation in
3676
- // Marionette applications
3677
- Marionette.Module = function(moduleName, app){
3678
- this.moduleName = moduleName;
3679
-
3680
- // store sub-modules
3681
- this.submodules = {};
3682
-
3683
- this._setupInitializersAndFinalizers();
3684
-
3685
- // store the configuration for this module
3686
- this.app = app;
3687
- this.startWithParent = true;
3688
-
3689
- this.triggerMethod = Marionette.triggerMethod;
3690
- };
3691
-
3692
- // Extend the Module prototype with events / listenTo, so that the module
3693
- // can be used as an event aggregator or pub/sub.
3694
- _.extend(Marionette.Module.prototype, Backbone.Events, {
3695
-
3696
- // Initializer for a specific module. Initializers are run when the
3697
- // module's `start` method is called.
3698
- addInitializer: function(callback){
3699
- this._initializerCallbacks.add(callback);
3700
- },
3701
-
3702
- // Finalizers are run when a module is stopped. They are used to teardown
3703
- // and finalize any variables, references, events and other code that the
3704
- // module had set up.
3705
- addFinalizer: function(callback){
3706
- this._finalizerCallbacks.add(callback);
3707
- },
3708
-
3709
- // Start the module, and run all of its initializers
3710
- start: function(options){
3711
- // Prevent re-starting a module that is already started
3712
- if (this._isInitialized){ return; }
3713
-
3714
- // start the sub-modules (depth-first hierarchy)
3715
- _.each(this.submodules, function(mod){
3716
- // check to see if we should start the sub-module with this parent
3717
- if (mod.startWithParent){
3718
- mod.start(options);
3719
- }
3720
- });
3721
-
3722
- // run the callbacks to "start" the current module
3723
- this.triggerMethod("before:start", options);
3724
-
3725
- this._initializerCallbacks.run(options, this);
3726
- this._isInitialized = true;
3727
-
3728
- this.triggerMethod("start", options);
3729
- },
3730
-
3731
- // Stop this module by running its finalizers and then stop all of
3732
- // the sub-modules for this module
3733
- stop: function(){
3734
- // if we are not initialized, don't bother finalizing
3735
- if (!this._isInitialized){ return; }
3736
- this._isInitialized = false;
3737
-
3738
- Marionette.triggerMethod.call(this, "before:stop");
3739
-
3740
- // stop the sub-modules; depth-first, to make sure the
3741
- // sub-modules are stopped / finalized before parents
3742
- _.each(this.submodules, function(mod){ mod.stop(); });
3743
-
3744
- // run the finalizers
3745
- this._finalizerCallbacks.run(undefined,this);
3746
-
3747
- // reset the initializers and finalizers
3748
- this._initializerCallbacks.reset();
3749
- this._finalizerCallbacks.reset();
3750
-
3751
- Marionette.triggerMethod.call(this, "stop");
3752
- },
3753
-
3754
- // Configure the module with a definition function and any custom args
3755
- // that are to be passed in to the definition function
3756
- addDefinition: function(moduleDefinition, customArgs){
3757
- this._runModuleDefinition(moduleDefinition, customArgs);
3758
- },
3759
-
3760
- // Internal method: run the module definition function with the correct
3761
- // arguments
3762
- _runModuleDefinition: function(definition, customArgs){
3763
- if (!definition){ return; }
3764
-
3765
- // build the correct list of arguments for the module definition
3766
- var args = _.flatten([
3767
- this,
3768
- this.app,
3769
- Backbone,
3770
- Marionette,
3771
- Marionette.$, _,
3772
- customArgs
3773
- ]);
3774
-
3775
- definition.apply(this, args);
3776
- },
3777
-
3778
- // Internal method: set up new copies of initializers and finalizers.
3779
- // Calling this method will wipe out all existing initializers and
3780
- // finalizers.
3781
- _setupInitializersAndFinalizers: function(){
3782
- this._initializerCallbacks = new Marionette.Callbacks();
3783
- this._finalizerCallbacks = new Marionette.Callbacks();
3784
- }
3785
- });
3786
-
3787
- // Type methods to create modules
3788
- _.extend(Marionette.Module, {
3789
-
3790
- // Create a module, hanging off the app parameter as the parent object.
3791
- create: function(app, moduleNames, moduleDefinition){
3792
- var module = app;
3793
-
3794
- // get the custom args passed in after the module definition and
3795
- // get rid of the module name and definition function
3796
- var customArgs = slice(arguments);
3797
- customArgs.splice(0, 3);
3798
-
3799
- // split the module names and get the length
3800
- moduleNames = moduleNames.split(".");
3801
- var length = moduleNames.length;
3802
-
3803
- // store the module definition for the last module in the chain
3804
- var moduleDefinitions = [];
3805
- moduleDefinitions[length-1] = moduleDefinition;
3806
-
3807
- // Loop through all the parts of the module definition
3808
- _.each(moduleNames, function(moduleName, i){
3809
- var parentModule = module;
3810
- module = this._getModule(parentModule, moduleName, app);
3811
- this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
3812
- }, this);
3813
-
3814
- // Return the last module in the definition chain
3815
- return module;
3816
- },
3817
-
3818
- _getModule: function(parentModule, moduleName, app, def, args){
3819
- // Get an existing module of this name if we have one
3820
- var module = parentModule[moduleName];
3821
-
3822
- if (!module){
3823
- // Create a new module if we don't have one
3824
- module = new Marionette.Module(moduleName, app);
3825
- parentModule[moduleName] = module;
3826
- // store the module on the parent
3827
- parentModule.submodules[moduleName] = module;
3828
- }
3829
-
3830
- return module;
3831
- },
3832
-
3833
- _addModuleDefinition: function(parentModule, module, def, args){
3834
- var fn;
3835
- var startWithParent;
3836
-
3837
- if (_.isFunction(def)){
3838
- // if a function is supplied for the module definition
3839
- fn = def;
3840
- startWithParent = true;
3841
-
3842
- } else if (_.isObject(def)){
3843
- // if an object is supplied
3844
- fn = def.define;
3845
- startWithParent = def.startWithParent;
3846
-
3847
- } else {
3848
- // if nothing is supplied
3849
- startWithParent = true;
3850
- }
3851
-
3852
- // add module definition if needed
3853
- if (fn){
3854
- module.addDefinition(fn, args);
3855
- }
3856
-
3857
- // `and` the two together, ensuring a single `false` will prevent it
3858
- // from starting with the parent
3859
- module.startWithParent = module.startWithParent && startWithParent;
3860
-
3861
- // setup auto-start if needed
3862
- if (module.startWithParent && !module.startWithParentIsConfigured){
3863
-
3864
- // only configure this once
3865
- module.startWithParentIsConfigured = true;
3866
-
3867
- // add the module initializer config
3868
- parentModule.addInitializer(function(options){
3869
- if (module.startWithParent){
3870
- module.start(options);
3871
- }
3872
- });
3873
-
3874
- }
3875
-
3876
- }
3877
- });
3878
-
3879
-
3880
-
3881
- return Marionette;
3882
- })(this, Backbone, _);
3883
-
3884
- /*!
3885
- * Tableling v0.0.21
3886
- * Copyright (c) 2012-2013 Simon Oulevay (Alpha Hydrae) <hydrae.alpha@gmail.com>
3887
- * Distributed under MIT license
3888
- * https://github.com/AlphaHydrae/tableling
3889
- */
3890
- Backbone.Tableling = Tableling = (function(Backbone, _, $){
3891
-
3892
- var Tableling = {
3893
- version : "0.0.21"
3894
- };
3895
-
3896
- // Tableling
3897
- // ---------
3898
- //
3899
- // A tableling table is a Marionette layout which fetches data
3900
- // from a Backbone collection. It is controlled with an EventAggregator.
3901
- Tableling.Table = Backbone.Marionette.Layout.extend({
3902
-
3903
- className: 'tableling',
3904
-
3905
- // Default table options can be overriden by subclasses.
3906
- config : {
3907
- page : 1
3908
- },
3909
-
3910
- initialize : function(options) {
3911
- options = options || {};
3912
-
3913
- this.collection = options.collection;
3914
-
3915
- // Table options can also be overriden for each instance at construction.
3916
- this.config = _.extend(_.clone(this.config || {}), _.result(options, 'config') || {});
3917
-
3918
- // We use an event aggregator to manage the layout and its components.
3919
- // You can use your own by passing a `vent` option.
3920
- this.vent = options.vent || new Backbone.Wreqr.EventAggregator();
3921
-
3922
- this.fetchOptions = _.extend(_.clone(this.fetchOptions || {}), _.result(options, 'fetchOptions') || {});
3923
- this.autoUpdate = typeof(options.autoUpdate) != 'undefined' ? options.autoUpdate : true;
3924
-
3925
- // Components should trigger the `table:update` event to update
3926
- // the table (e.g. change page size, sort) and fetch the new data.
3927
- this.vent.on('table:update', this.onUpdate, this);
3928
-
3929
- this.on('item:rendered', this.setup, this);
3930
- },
3931
-
3932
- // Called once rendering is complete. By default, it updates the table.
3933
- setup : function() {
3934
- this.ventTrigger('table:setup', this.config);
3935
- if (this.autoUpdate) {
3936
- this.ventTrigger('table:update');
3937
- }
3938
- },
3939
-
3940
- // Subclasses must return the Backbone.Collection used to fetch data.
3941
- getCollection : function() {
3942
- return this.collection;
3943
- },
3944
-
3945
- // ### Refreshing the table
3946
- update : function(config, options) {
3947
- this.ventTrigger('table:update', config, options);
3948
- },
3949
-
3950
- onUpdate : function(config, options) {
3951
-
3952
- _.each(config || {}, _.bind(this.updateValue, this));
3953
-
3954
- // Set the `refresh` option to false to update the table configuration
3955
- // without refreshing.
3956
- if (!options || typeof(options.refresh) == 'undefined' || options.refresh) {
3957
- this.refresh();
3958
- }
3959
- },
3960
-
3961
- updateValue : function(value, key) {
3962
- if (value && value.toString().length) {
3963
- this.config[key] = value;
3964
- } else {
3965
- // Blank values are deleted to avoid sending them in ajax requests.
3966
- delete this.config[key];
3967
- }
3968
- },
3969
-
3970
- refresh : function() {
3971
-
3972
- // You can provide `fetchOptions` to add properties to the
3973
- // fetch request.
3974
- //
3975
- // var MyTable = Tableling.Table.extend({
3976
- // fetchOptions : {
3977
- // type : 'POST' // fetch data with POST
3978
- // }
3979
- // });
3980
- //
3981
- // // You can also override for each instance.
3982
- // new MyTable({
3983
- // fetchOptions : {
3984
- // type : 'GET'
3985
- // }
3986
- // });
3987
- var options = _.clone(this.fetchOptions);
3988
- options.data = this.requestData();
3989
- options.success = _.bind(this.processResponse, this);
3990
-
3991
- // `table:refreshing` is triggered every time new data is being fetched.
3992
- // The first argument is the request data.
3993
- this.ventTrigger('table:refreshing', options.data);
3994
-
3995
- this.getCollection().fetch(options);
3996
- },
3997
-
3998
- // ### Request
3999
- requestData : function() {
4000
- return this.config;
4001
- },
4002
-
4003
- // ### Response
4004
- processResponse : function(collection, response) {
4005
-
4006
- this.config.length = collection.length;
4007
-
4008
- // Tableling expects the response from a fetch to have a `total` property
4009
- // which is the total number of items (not just in the current page).
4010
- this.config.total = response.total;
4011
-
4012
- // The server may override the `page` property, for example if the
4013
- // requested page was outside the range of available pages.
4014
- if (response.page) {
4015
- this.config.page = response.page;
4016
- }
4017
-
4018
- // `tableling:refreshed` is triggered after every refresh. The first argument
4019
- // is the current table configuration with the following additional meta data:
4020
- //
4021
- // * `total` - the total number of items
4022
- // * `length` - the number of items in the current page
4023
- this.ventTrigger('table:refreshed', this.config);
4024
- },
4025
-
4026
- // Triggers an event in the event aggregator. If `Tableling.debug` is set, it also
4027
- // logs the event and its arguments.
4028
- ventTrigger : function() {
4029
-
4030
- var args = Array.prototype.slice.call(arguments);
4031
- if (Tableling.debug) {
4032
- console.log(_.first(args) + ' - ' + JSON.stringify(args.slice(1)));
4033
- }
4034
-
4035
- this.vent.trigger.apply(this.vent, args);
4036
- }
4037
- });
4038
-
4039
- // Tableling.Collection
4040
- // --------------------
4041
- //
4042
- // Tableling expects fetch responses to have a `total` property in addition
4043
- // to the model data. You can extend this Backbone.Collection subclass which
4044
- // expects the following response format:
4045
- //
4046
- // {
4047
- // "total": 12,
4048
- // "data": [
4049
- // { /* ... model data ... */ },
4050
- // { /* ... model data ... */ }
4051
- // ]
4052
- // }
4053
- Tableling.Collection = Backbone.Collection.extend({
4054
-
4055
- parse : function(response) {
4056
- return response.data;
4057
- }
4058
- });
4059
-
4060
- // Implementations
4061
- // ---------------
4062
- //
4063
- // <a href="tableling.bootstrap.html">tableling.bootstrap</a> provides views styled
4064
- // with [Twitter Bootstrap](http://twitter.github.com/bootstrap/) classes.
4065
-
4066
- // Tableling.Modular
4067
- // -----------------
4068
- //
4069
- // Tableling subclass which splits functionality into *modules*
4070
- // and handles rendering.
4071
- Tableling.Modular = Tableling.Table.extend({
4072
-
4073
- // The list of module names must be specified by subclasses.
4074
- modules : [],
4075
-
4076
- // Modules are set up after rendering, before refreshing.
4077
- setup : function() {
4078
-
4079
- this.moduleViews = {};
4080
- _.each(this.modules, _.bind(this.setupModule, this));
4081
-
4082
- Tableling.Table.prototype.setup.call(this);
4083
- },
4084
-
4085
- // ### Modules
4086
- // Each module is identified by a name, for example `pageSize`.
4087
- setupModule : function(name) {
4088
-
4089
- // The layout must have a region named after the module, e.g. `pageSizeRegion`.
4090
- var region = name + 'Region';
4091
-
4092
- // It must have a view class, e.g. `pageSizeView`, which will be shown into
4093
- // the region.
4094
- var viewClass = this[name + 'View'];
4095
-
4096
- // When instantiated, the view class will be passed the event
4097
- // aggregator as the `vent` option. Additional options can be
4098
- // given named after the view class, e.g. `pageSizeViewOptions`.
4099
- var options = _.extend(this.getModuleOptions(name), { vent: this.vent });
4100
-
4101
- var view = new viewClass(options);
4102
-
4103
- // Module view instances are stored by name in the `moduleViews` property
4104
- // for future reference.
4105
- this.moduleViews[name] = view;
4106
-
4107
- this[region].show(view);
4108
- return view;
4109
- },
4110
-
4111
- // By default the collection is the one given at construction.
4112
- // Otherwise, a modular table expects a `table` module which
4113
- // should have a collection (e.g. a Marionette CompositeView or
4114
- // CollectionView). If your subclass does not have either, it
4115
- // should override this method to return the Backbone.Collection
4116
- // used to fetch table data.
4117
- getCollection : function() {
4118
- return this.collection || (this.moduleViews && this.moduleViews.table ? this.moduleViews.table.collection : undefined);
4119
- },
4120
-
4121
- getModuleOptions : function(name) {
4122
- var options = this[name + 'ViewOptions'] || {};
4123
- options = typeof(options) == 'function' ? options.call(this) : options;
4124
- return name == 'table' ? _.defaults(options, { collection : this.collection }) : options;
4125
- }
4126
- });
4127
-
4128
- // ### Example
4129
- // This is how a `PageSizeView` module might be registered in a subclass:
4130
- //
4131
- // var MyTable = Tableling.Modular.extend({
4132
- //
4133
- // modules : [ 'pageSize' ],
4134
- //
4135
- // pageSizeView : PageSizeView,
4136
- // pageSizeViewOptions : {
4137
- // itemView : PageSizeItem
4138
- // },
4139
- //
4140
- // regions : {
4141
- // pageSizeRegion : '.pageSize'
4142
- // }
4143
- // });
4144
-
4145
- // Tableling.Module
4146
- // ----------------
4147
- //
4148
- // A module is an item view that is automatically bound to the table's
4149
- // event aggregator.
4150
- Tableling.Module = Backbone.Marionette.ItemView.extend({
4151
-
4152
- i18n : {},
4153
- templateHelpers : function() {
4154
- return this.i18n;
4155
- },
4156
-
4157
- initialize : function(options) {
4158
-
4159
- this.vent = options.vent;
4160
-
4161
- // The `setup` method of the view is called when the table
4162
- // is first set up.
4163
- this.vent.on('table:setup', this.setup, this);
4164
-
4165
- // The `refresh` method of the view is called every time the table
4166
- // is refreshed.
4167
- this.vent.on('table:refreshed', this.refresh, this);
4168
-
4169
- this.i18n = _.clone(options.i18n || this.i18n);
4170
- },
4171
-
4172
- // Call `update` to trigger an update of the table.
4173
- update : function() {
4174
- this.vent.trigger('table:update', this.config());
4175
- },
4176
-
4177
- // Implementations should override this to set initial values.
4178
- setup : function(config) {
4179
- },
4180
-
4181
- // Implementations should override this to stay up to date with
4182
- // the table state.
4183
- refresh : function(config) {
4184
- },
4185
-
4186
- // New table configuration to be sent on updates. For example,
4187
- // a page size view might update the `pageSize` property.
4188
- config : function() {
4189
- return {};
4190
- }
4191
- });
4192
-
4193
- // Tableling.FieldModule
4194
- // ---------------------
4195
- //
4196
- // A basic module with a single form field. It comes with sensible
4197
- // defaults and only requires a `name` and a `template` parameter.
4198
- Tableling.FieldModule = Tableling.Module.extend({
4199
-
4200
- // TODO: check name
4201
-
4202
- initialize : function(options) {
4203
-
4204
- Tableling.Module.prototype.initialize.call(this, options);
4205
-
4206
- if (!this.ui) {
4207
- this.ui = {};
4208
- }
4209
- // The name attribute of the form field is the same as the
4210
- // module's, e.g. `pageSize`.
4211
- this.ui.field = '[name="' + this.name + '"]';
4212
-
4213
- if (!this.events) {
4214
- this.events = {};
4215
- }
4216
- this.events['change [name="' + this.name + '"]'] = 'update';
4217
- },
4218
-
4219
- setup : function(config) {
4220
- this.ui.field.val(config[this.name]);
4221
- this.vent.trigger('table:update', this.config(), { refresh : false });
4222
- },
4223
-
4224
- // The table property updated is the one with the same name as the module.
4225
- config : function() {
4226
- var config = {};
4227
- config[this.name] = this.ui.field.val();
4228
- return config;
4229
- }
4230
- });
4231
-
4232
- // This is how a `PageSizeView` module might be implemented:
4233
- //
4234
- // var html = '<input type="text" name="pageSize" />';
4235
- //
4236
- // var PageSizeView = Tableling.FieldModule.extend({
4237
- // name : 'pageSize'
4238
- // template : _.template(html)
4239
- // });
4240
- //
4241
- // When the value of the input field changes, the event aggregator will
4242
- // receive a `tableling:update` event with the `pageSize` property set
4243
- // to that value.
4244
-
4245
- Tableling.Plain = {};
4246
-
4247
- Tableling.Plain.Table = Tableling.Modular.extend({
4248
-
4249
- className: 'tableling',
4250
- modules : [ 'table', 'pageSize', 'quickSearch', 'info', 'page' ],
4251
- template : _.template('<div class="header"><div class="pageSize" /><div class="quickSearch" /></div><div class="table" /><div class="footer"><div class="info" /><div class="page" /></div>'),
4252
-
4253
- regions : {
4254
- tableRegion : '.table',
4255
- pageSizeRegion : '.pageSize',
4256
- quickSearchRegion : '.quickSearch',
4257
- infoRegion : '.info',
4258
- pageRegion : '.page'
4259
- }
4260
- });
4261
-
4262
- Tableling.Plain.TableView = Backbone.Marionette.CompositeView.extend({
4263
-
4264
- events : {
4265
- 'click thead th.sorting' : 'updateSort',
4266
- 'click thead th.sorting-asc' : 'updateSort',
4267
- 'click thead th.sorting-desc' : 'updateSort'
4268
- },
4269
-
4270
- initialize : function(options) {
4271
- // TODO: add auto-sort
4272
- this.vent = options.vent;
4273
- this.sort = [];
4274
- this.vent.on('table:setup', this.setSort, this);
4275
- this.vent.on('table:refreshed', this.setSort, this);
4276
- },
4277
-
4278
- updateSort : function(ev) {
4279
-
4280
- var el = $(ev.currentTarget);
4281
- if (!(el.hasClass('sorting') || el.hasClass('sorting-asc') || el.hasClass('sorting-desc'))) {
4282
- return;
4283
- }
4284
-
4285
- var field = this.fieldName(el);
4286
-
4287
- if (ev.shiftKey || this.sort.length == 1) {
4288
-
4289
- var index = -1;
4290
- _.find(this.sort, function(item, i) {
4291
- if (item.split(' ')[0] == field) {
4292
- index = i;
4293
- }
4294
- });
4295
-
4296
- if (index >= 0) {
4297
-
4298
- var parts = this.sort[index].split(' ');
4299
- this.sort[index] = parts[0] + ' ' + (parts[1] == 'asc' ? 'desc' : 'asc');
4300
- this.showSort();
4301
- return this.vent.trigger('table:update', this.config());
4302
- }
4303
- }
4304
-
4305
- if (!ev.shiftKey) {
4306
- this.sort.length = 0;
4307
- }
4308
-
4309
- this.sort.push(field + ' asc');
4310
-
4311
- this.showSort();
4312
-
4313
- this.vent.trigger('table:update', this.config());
4314
- },
4315
-
4316
- setSort : function(config) {
4317
- if (config && config.sort) {
4318
- this.sort = config.sort.slice(0);
4319
- this.showSort();
4320
- }
4321
- },
4322
-
4323
- showSort : function() {
4324
-
4325
- this.$el.find('thead th.sorting, thead th.sorting-asc, thead th.sorting-desc').removeClass('sorting sorting-asc sorting-desc').addClass('sorting');
4326
-
4327
- for (var i = 0; i < this.sort.length; i++) {
4328
-
4329
- var parts = this.sort[i].split(' ');
4330
- var name = parts[0];
4331
- var direction = parts[1];
4332
-
4333
- field = this.$el.find('thead [data-field="' + name + '"]');
4334
- if (!field.length) {
4335
- field = this.$el.find('thead th:contains("' + name + '")');
4336
- }
4337
-
4338
- if (field.length) {
4339
- field.removeClass('sorting').addClass(direction == 'desc' ? 'sorting-desc' : 'sorting-asc');
4340
- }
4341
- }
4342
- },
4343
-
4344
- config : function() {
4345
- return {
4346
- page : 1,
4347
- sort : this.sortConfig()
4348
- };
4349
- },
4350
-
4351
- sortConfig : function() {
4352
- return this.sort.length ? this.sort : null;
4353
- },
4354
-
4355
- fieldName : function(el) {
4356
- return el.data('field') || el.text();
4357
- }
4358
- });
4359
-
4360
- Tableling.Plain.PageSizeView = Tableling.Plain.Table.prototype.pageSizeView = Tableling.FieldModule.extend({
4361
-
4362
- // TODO: update current page intelligently
4363
- name : 'pageSize',
4364
- template : function(data) {
4365
- return _.template('<select name="pageSize" /> <%- entries %>', data);
4366
- },
4367
-
4368
- i18n : {
4369
- entries : 'entries per page'
4370
- },
4371
- sizes : [ 10, 15, 20, 25, 50 ],
4372
-
4373
- ui : {
4374
- field : 'select'
4375
- },
4376
-
4377
- initialize : function(options) {
4378
- Tableling.FieldModule.prototype.initialize.call(this, options);
4379
- this.sizes = _.clone(options.sizes || this.sizes);
4380
- },
4381
-
4382
- onRender : function() {
4383
- this.ui.field.empty();
4384
- _.each(this.sizes, _.bind(this.addSize, this));
4385
- },
4386
-
4387
- addSize : function(size) {
4388
- $('<option />').text(size).appendTo(this.ui.field);
4389
- },
4390
-
4391
- config : function() {
4392
- var config = Tableling.FieldModule.prototype.config.call(this);
4393
- config.page = 1;
4394
- return config;
4395
- }
4396
- });
4397
-
4398
- Tableling.Plain.QuickSearchView = Tableling.Plain.Table.prototype.quickSearchView = Tableling.FieldModule.extend({
4399
-
4400
- name : 'quickSearch',
4401
- template : function(data) {
4402
- return _.template('<input type="text" name="quickSearch" placeholder="<%- quickSearch %>" />', data);
4403
- },
4404
-
4405
- i18n : {
4406
- quickSearch : 'Quick search...'
4407
- },
4408
-
4409
- config : function() {
4410
- var config = Tableling.FieldModule.prototype.config.call(this);
4411
- config.page = 1;
4412
- return config;
4413
- }
4414
- });
4415
-
4416
- Tableling.Plain.InfoView = Tableling.Plain.Table.prototype.infoView = Tableling.Module.extend({
4417
-
4418
- template : function(data) {
4419
- return _.template(data.template, {
4420
- first : '<span class="first">0</span>',
4421
- last : '<span class="last">0</span>',
4422
- total : '<span class="total">0</span>'
4423
- });
4424
- },
4425
-
4426
- i18n : {
4427
- template : 'Showing <%= first %> to <%= last %> of <%= total %> entries'
4428
- },
4429
-
4430
- ui : {
4431
- first: '.first',
4432
- last: '.last',
4433
- total: '.total'
4434
- },
4435
-
4436
- refresh : function(data) {
4437
- if (data) {
4438
- this.ui.first.text(this.firstRecord(data));
4439
- this.ui.last.text(this.lastRecord(data));
4440
- this.ui.total.text(data.total);
4441
- }
4442
- },
4443
-
4444
- firstRecord : function(data) {
4445
- return data.length ? ((data.page || 1) - 1) * data.pageSize + 1 : 0;
4446
- },
4447
-
4448
- lastRecord : function(data) {
4449
- return data.length ? this.firstRecord(data) + data.length - 1 : 0;
4450
- }
4451
- });
4452
-
4453
- Tableling.Plain.PageView = Tableling.Plain.Table.prototype.pageView = Tableling.Module.extend({
4454
-
4455
- template : _.template('<div class="pagination"><ul><li class="first"><a href="#">&lt;&lt;</a></li><li class="previous"><a href="#">&lt;</a></li><li class="next"><a href="#">&gt;</a></li><li class="last"><a href="#">&gt;&gt;</a></li></ul></div>'),
4456
- pageTemplate : _.template('<li class="page"><a href="#"><%- number %></a></li>'),
4457
-
4458
- ui : {
4459
- first : '.first',
4460
- previous : '.previous',
4461
- next : '.next',
4462
- last : '.last'
4463
- },
4464
-
4465
- events : {
4466
- 'click .first:not(.disabled)' : 'goToFirstPage',
4467
- 'click .previous:not(.disabled)' : 'goToPreviousPage',
4468
- 'click .page:not(.disabled)' : 'goToPage',
4469
- 'click .next:not(.disabled)' : 'goToNextPage',
4470
- 'click .last:not(.disabled)' : 'goToLastPage'
4471
- },
4472
-
4473
- refresh : function(data) {
4474
- this.$el.find('.page').remove();
4475
- if (!data || !data.length) {
4476
- this.ui.first.addClass('disabled');
4477
- this.ui.previous.addClass('disabled');
4478
- this.ui.next.addClass('disabled');
4479
- this.ui.last.addClass('disabled');
4480
- } else {
4481
- this.data = data;
4482
- this.enable(this.ui.first, this.getPage(data) > 1);
4483
- this.enable(this.ui.previous, this.getPage(data) > 1);
4484
- this.setupPages();
4485
- this.enable(this.ui.next, this.getPage(data) < this.numberOfPages(data));
4486
- this.enable(this.ui.last, this.getPage(data) < this.numberOfPages(data));
4487
- }
4488
- },
4489
-
4490
- setupPages : function() {
4491
-
4492
- var page = this.getPage(this.data);
4493
- var total = this.numberOfPages();
4494
-
4495
- var first = page - 2;
4496
- if (total - first < 4) {
4497
- first = total - 4;
4498
- }
4499
-
4500
- if (first < 1) {
4501
- first = 1;
4502
- }
4503
-
4504
- var n = 5;
4505
- if (first + n - 1 > total) {
4506
- n = total - first + 1;
4507
- }
4508
-
4509
- _.times(n, function(i) {
4510
- $(this.pageTemplate({ number : first + i })).insertBefore(this.ui.next);
4511
- }, this);
4512
-
4513
- var i = page - first;
4514
- this.$el.find('.page').slice(i, i + 1).addClass('disabled');
4515
- },
4516
-
4517
- enable : function(el, enabled) {
4518
- el.removeClass('disabled');
4519
- if (!enabled) {
4520
- el.addClass('disabled');
4521
- }
4522
- },
4523
-
4524
- numberOfPages : function() {
4525
- return Math.ceil(this.data.total / this.data.pageSize);
4526
- },
4527
-
4528
- goToFirstPage : function(e) {
4529
- e.preventDefault();
4530
- this.goToPageNumber(1);
4531
- },
4532
-
4533
- goToPreviousPage : function(e) {
4534
- e.preventDefault();
4535
- this.goToPageNumber(this.getPage(this.data) - 1);
4536
- },
4537
-
4538
- goToPage : function(e) {
4539
- e.preventDefault();
4540
- this.goToPageNumber(parseInt($(e.target).text(), 10));
4541
- },
4542
-
4543
- goToNextPage : function(e) {
4544
- e.preventDefault();
4545
- this.goToPageNumber(this.getPage(this.data) + 1);
4546
- },
4547
-
4548
- goToLastPage : function(e) {
4549
- e.preventDefault();
4550
- this.goToPageNumber(this.numberOfPages());
4551
- },
4552
-
4553
- goToPageNumber : function(n) {
4554
- this.vent.trigger('table:update', { page : n });
4555
- },
4556
-
4557
- getPage : function(data) {
4558
- return data.page || 1;
4559
- }
4560
- });
4561
-
4562
- Tableling.Bootstrap = {};
4563
-
4564
- Tableling.Bootstrap.Table = Tableling.Plain.Table.extend({
4565
- template : _.template('<div class="header"><div class="pageSize pull-left" /><div class="quickSearch pull-right" /></div><div class="table" /><div class="footer"><div class="info pull-left" /><div class="page pull-right" /></div>')
4566
- });
4567
-
4568
- Tableling.Bootstrap.TableView = Tableling.Plain.TableView.extend({});
4569
-
4570
- Tableling.Bootstrap.PageSizeView = Tableling.Bootstrap.Table.prototype.pageSizeView = Tableling.Plain.PageSizeView.extend({
4571
-
4572
- template : function(data) {
4573
- return _.template('<select name="pageSize" class="input-mini"><option>5</option><option>10</option><option>15</option></select> <%- entries %>', data);
4574
- }
4575
- });
4576
-
4577
- Tableling.Bootstrap.QuickSearchView = Tableling.Bootstrap.Table.prototype.quickSearchView = Tableling.Plain.QuickSearchView.extend({});
4578
-
4579
- Tableling.Bootstrap.InfoView = Tableling.Bootstrap.Table.prototype.infoView = Tableling.Plain.InfoView.extend({});
4580
-
4581
- Tableling.Bootstrap.PageView = Tableling.Bootstrap.Table.prototype.pageView = Tableling.Plain.PageView.extend({});
4582
-
4583
-
4584
- return Tableling;
4585
-
4586
- })(Backbone, _, $ || window.jQuery || window.Zepto || window.ender);