-
Notifications
You must be signed in to change notification settings - Fork 6
/
ckanjs.js
1975 lines (1766 loc) · 59.4 KB
/
ckanjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
this.CKAN = this.CKAN || {};
this.CKAN.Client = (function (CKAN, $, _, Backbone, undefined) {
// Client constructor. Creates a new client for communicating with
// the CKAN API.
function Client(config) {
this._environment = {};
this.configure(config || Client.defaults);
_.bindAll(this, 'syncDataset', '_datasetConverter', 'syncGroup');
}
// Default config parameters for the Client.
Client.defaults = {
apiKey: '',
endpoint: 'http://ckan.net'
};
// Extend the Client prototype with Backbone.Events to provide .bind(),
// .unbind() and .trigger() methods.
_.extend(Client.prototype, Backbone.Events, {
cache: {
dataset: new Backbone.Collection(),
group: new Backbone.Collection()
},
// Allows the implementor to specify an object literal of settings to
// configure the current client. Options include:
//
// - apiKey: The API key for the current user to create/edit datasets.
// - endpoint: The API endpoint to connect to.
configure: function (config) {
config = config || {};
if (config.endpoint) {
config.endpoint = config.endpoint.replace(/\/$/, '');
config.restEndpoint = config.endpoint + '/api/2/rest';
config.searchEndpoint = config.endpoint + '/api/2/search';
}
return this.environment(config);
},
// Client environment getter/setter. Environment variables can be retrieved
// by providing a key string, if the key does not exist the method will
// return `undefined`. To set keys either a key value pair can be provided
// or an object literal containing multiple key/value pairs.
environment: function (key, value) {
if (typeof key === "string") {
if (arguments.length === 1) {
return this._environment[key];
}
this._environment[key] = value;
} else {
_.extend(this._environment, key);
}
return this;
},
// Helper method to fetch datasets from the server. Using this method to
// fetch datasets will ensure that only one instance of a model per server
// resource exists on the page at one time.
//
// The method accepts the dataset `"id"` and an object of `"options"`, these
// can be any options accepted by the `.fetch()` method on `Backbone.Model`.
// If the model already exists it will simply be returned otherwise an empty
// model will be returned and the data requested from the server.
//
// var dataset = client.getDatasetById('my-data-id', {
// success: function () {
// // The model is now populated.
// },
// error: function (xhr) {
// // Something went wrong check response status etc.
// }
// });
//
getDatasetById: function (id, options) {
var cache = this.cache.dataset,
dataset = cache.get(id);
var ourOptions = options || {};
if (!dataset) {
dataset = this.createDataset({id: id});
// Add the stub dataset to the global cache to ensure that only one
// is ever created.
cache.add(dataset);
// Fetch the dataset from the server passing in any options provided.
// Also set up a callback to remove the model from the cache in
// case of error.
ourOptions.error = function () {
cache.remove(dataset);
};
// TODO: RP not sure i understand what this does and why it is needed
dataset.fetch(ourOptions);
}
return dataset;
},
// Helper method to create a new instance of CKAN.Model.Dataset and
// register a sync listener to update the representation on the server when
// the model is created/updated/deleted.
//
// var myDataset = client.createDataset({
// title: "My new data set"
// });
//
// This ensures that the models are always saved with the latest environment
// data.
createDataset: function (attributes) {
return (new CKAN.Model.Dataset(attributes)).bind('sync', this.syncDataset);
},
// A wrapper around Backbone.sync() that adds additional ajax options to
// each request. These include the API key and the request url rather than
// using the model to generate it.
syncDataset: function (method, model, options) {
// Get the package url.
var url = this.environment('restEndpoint') + '/package';
// Add additional request options.
options = _.extend({}, {
url: model.isNew() ? url : url + '/' + model.id,
headers: {
'X-CKAN-API-KEY': this.environment('apiKey')
}
}, options);
Backbone.sync(method, model, options);
return this;
},
// Performs a search for datasets against the CKAN API. The `options`
// argument can contain any keys supported by jQuery.ajax(). The query
// parameters should be provided in the `options.query` property.
//
// var query = client.searchDatasets({
// success: function (datasets) {
// console.log(datasets); // Logs a Backbone.Collection
// }
// });
//
// The `options.success` method (and any other success callbacks) will
// recieve a `SearchCollection` containing `Dataset` models. The method
// returns a jqXHR object so that additional callbacks can be registered
// with .success() and .error().
searchDatasets: function (options) {
options = options || {};
options.data = _.defaults(options.query, {'limit': 10, 'all_fields': 1});
delete options.query;
return $.ajax(_.extend({
url: this.environment('searchEndpoint') + '/package',
converters: {
'text json': this._datasetConverter
}
}, options));
},
// A "converter" method for jQuery.ajax() this is used to convert the
// results from a search API request into models which in turn will be
// passed into any registered success callbacks. We do this here so that
// _all_ registered success callbacks recieve the same data rather than
// just the callback registered when the search was made.
_datasetConverter: function (raw) {
var json = $.parseJSON(raw),
models = _.map(json.results, function (attributes) {
return this.createDataset(attributes);
}, this);
return new CKAN.Model.SearchCollection(models, {total: json.count});
},
getGroupById: function (id, options) {
var cache = this.cache.group,
group = cache.get(id);
var ourOptions = options || {};
if (!group) {
group = this.createGroup({id: id});
// Add the stub group to the global cache to ensure that only one
// is ever created.
cache.add(group);
// Fetch the group from the server passing in any options provided.
// Also set up a callback to remove the model from the cache in
// case of error.
ourOptions.error = function () {
cache.remove(group);
};
// TODO: RP not sure i understand what this does and why it is needed
group.fetch(ourOptions);
}
return group;
},
createGroup: function (attributes) {
return (new CKAN.Model.Group(attributes)).bind('sync', this.syncGroup);
},
// A wrapper around Backbone.sync() that adds additional ajax options to
// each request. These include the API key and the request url rather than
// using the model to generate it.
syncGroup: function (method, model, options) {
// Get the package url.
var url = this.environment('restEndpoint') + '/group';
// Add additional request options.
options = _.extend({}, {
url: model.isNew() ? url : url + '/' + model.id,
headers: {
'X-CKAN-API-KEY': this.environment('apiKey')
}
}, options);
Backbone.sync(method, model, options);
return this;
},
searchGroups: function (options) {
options = options || {};
options.data = _.defaults(options.query, {'limit': 10, 'all_fields': 1});
delete options.query;
return $.ajax(_.extend({
url: this.environment('searchEndpoint') + '/package',
converters: {
'text json': this._datasetConverter
}
}, options));
},
// Get a list of Groups by dataset count with option to filter by a specific existing group.
getTopGroups: function(filterGroup, success, error) {
var self = this;
var data = {
'facet.field': 'groups',
'rows': 0
};
if (filterGroup) {
data.fq = 'groups:' + filterGroup;
}
var options = {
type: 'POST',
offset: '/action/package_search',
data: JSON.stringify(data),
success: function(data) {
var groups = processResults(data);
success(groups);
}
};
function processResults(data) {
var groups = _.map(data.result.facets.groups, function(count, key) {
return {
id: key,
count: count
};
});
groups = _.sortBy(groups, function(item) {
return -item.count;
});
// TODO: exclude the group we filtered by ...
var groupObjs = _.map(groups, function(groupInfo) {
var group = self.getGroupById(groupInfo.id);
group.set({filtered_dataset_count: groupInfo.count});
return group;
});
return groupObjs;
}
this.apiCall(options);
},
// Performs a query on CKAN API.
// The `options` argument can contain any keys supported by jQuery.ajax().
// In addition it should contain either a url or offset variable. If
// offset provided it will be used to construct the full api url by
// prepending the endpoint plus 'api' (i.e. offset of '/2/rest/package'
// will become '{endpoint}/api/2/rest'.
//
// The `options.success` method (and any other success callbacks) will
// recieve a `SearchCollection` containing `Dataset` models. The method
// returns a jqXHR object so that additional callbacks can be registered
// with .success() and .error().
apiCall: function (options) {
options = options || {};
var offset = options.offset || '';
delete options.offset;
// Add additional request options.
options = _.extend({}, {
url: this.environment('endpoint') + '/api' + offset,
headers: {
'X-CKAN-API-KEY': this.environment('apiKey')
}
}, options);
return $.ajax(options);
},
// wrap CKAN /api/storage/auth/form - see http://packages.python.org/ckanext-storage
// params and returns value are as for that API
// key is file label/path
getStorageAuthForm: function(key, options) {
options.offset = '/storage/auth/form/' + key;
this.apiCall(options);
}
});
return Client;
})(this.CKAN, this.$, this._, this.Backbone);
this.CKAN = this.CKAN || {};
// Global object that stores all CKAN models.
CKAN.Model = function ($, _, Backbone, undefined) {
var Model = {};
// Simple validator helper returns a `validate()` function that checks
// the provided model keys and returns an error object if these do not
// exist on the model or the attributes object provided.\
//
// validate: validator('title', 'description', url)
//
function validator() {
var required = arguments;
return function (attrs) {
var errors;
if (attrs) {
_.each(required, function (key) {
if (!attrs[key] && !this.get(key)) {
if (!errors) {
errors = {};
}
errors[key] = 'The "' + key + '" is required';
}
}, this);
}
return errors;
};
}
// A Base model that all CKAN models inherit from. Methods that should be
// shared across all models should be defined here.
Model.Base = Backbone.Model.extend({
// Extend the default Backbone.Model constructor simply to provide a named
// function. This improves debugging in consoles such as the Webkit inspector.
constructor: function Base(attributes, options) {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
// Rather than letting the models connect to the server themselves we
// leave this to the implementor to decide how models are saved. This allows
// the API details such as API key and enpoints to change without having
// to update the models. When `.save()` or `.destroy()` is called the
// `"sync"` event will be published with the arguments provided to `.sync()`.
//
// var package = new Package({name: 'My Package Name'});
// package.bind('sync', Backbone.sync);
//
// This method returns itself for chaining.
sync: function () {
return this.trigger.apply(this, ['sync'].concat(_.toArray(arguments)));
},
// Overrides the standard `toJSON()` method to serialise any nested
// Backbone models and collections (or any other object that has a `toJSON()`
// method).
toJSON: function () {
var obj = Backbone.Model.prototype.toJSON.apply(this, arguments);
_.each(obj, function (value, key) {
if (value && typeof value === 'object' && value.toJSON) {
obj[key] = value.toJSON();
}
});
return obj;
}
});
// Model objects
Model.Dataset = Model.Base.extend({
constructor: function Dataset() {
// Define an key/model mapping for child relationships. These will be
// managed as a Backbone collection when setting/getting the key.
this.children = {
resources: Model.Resource,
relationships: Model.Relationship
};
Model.Base.prototype.constructor.apply(this, arguments);
},
defaults: {
title: '',
name: '',
notes: '',
resources: [],
tags: []
},
// Override the `set()` method on `Backbone.Model` to handle resources as
// relationships. This will now manually update the `"resouces"` collection
// (using `_updateResources()`) with any `Resource` models provided rather
// than replacing the key.
set: function (attributes, options) {
var children, validated;
// If not yet defined set the child collections. This will be done when
// set is called for the first time in the constructor.
this._createChildren();
// Check to see if any child keys are present in the attributes and
// remove them from the object. Then update them seperately after the
// parent `set()` method has been called.
_.each(this.children, function (Model, key) {
if (attributes && attributes[key]) {
if (!(attributes[key] instanceof Backbone.Collection)) {
if (!children) {
children = {};
}
children[key] = attributes[key];
delete attributes[key];
}
}
}, this);
validated = Model.Base.prototype.set.call(this, attributes, options);
// Ensure validation passed before updating child models.
if (validated && children) {
this._updateChildren(children);
}
return validated;
},
// Checks to see if our model instance has Backbone collections defined for
// child keys. If they do not exist it creates them.
_createChildren: function () {
_.each(this.children, function (Model, key) {
if (!this.get(key)) {
var newColl = new Backbone.Collection();
this.attributes[key] = newColl;
newColl.model = Model;
// bind change events so updating the children trigger change on Dataset
var self = this;
// TODO: do we want to do all or be more selective
newColl.bind('all', function() {
self.trigger('change');
});
}
}, this);
return this;
},
// Manages the one to many relationship between resources and the dataset.
// Accepts an array of Resources (ideally model instances but will convert
// object literals into resources for you). New models will be added to the
// collection and existing ones updated. Any pre-existing models not found
// in the new array will be removed.
_updateChildren: function (children) {
_.each(children, function (models, key) {
var collection = this.get(key),
ids = {};
// Add/Update models.
_.each(models, function (model) {
var existing = collection.get(model.id),
isLiteral = !(model instanceof this.children[key]);
// Provide the dataset key if not already there and current model is
// not a relationship.
if (isLiteral && key !== 'relationships') {
model.dataset = this;
delete model.package_id;
}
if (!existing) {
collection.add(model);
}
else if (existing && isLiteral) {
existing.set(model);
}
ids[model.id] = 1;
}, this);
// Remove missing models.
collection.remove(collection.select(function (model) {
return !ids[model.id];
}));
}, this);
return this;
},
// NOTE: Returns localised URL.
toTemplateJSON: function () {
var out = this.toJSON();
var title = this.get('title');
out.displaytitle = title ? title : 'No title ...';
var notes = this.get('notes');
// Don't use a global Showdown; CKAN doesn't need that library
var showdown = new Showdown.converter();
out.notesHtml = showdown.makeHtml(notes ? notes : '');
out.snippet = this.makeSnippet(out.notesHtml);
return out;
},
makeSnippet: function (notesHtml) {
var out = $(notesHtml).text();
if (out.length > 190) {
out = out.slice(0, 190) + ' ...';
}
return out;
}
});
// A model for working with resources. Each resource is _required_ to have a
// parent `Dataset`. This must be provided under the `"dataset"` key when the
// `Resource` is created. This is handled for you when creating resources
// via the `Dataset` `set()` method.
//
// The `save()`, `fetch()` and `delete()` methods are mapped to the parent
// dataset and can be used to update a Resource's metadata.
//
// var resource = new Model.Resource({
// name: 'myresource.csv',
// url: 'http://www.example.com/myresource.csv',
// dataset: dataset
// });
//
// // Updates the resource name on the server by saving the parent dataset
// resource.set({name: 'Some new name'});
//
Model.Resource = Model.Base.extend({
constructor: function Resource() {
Model.Base.prototype.constructor.apply(this, arguments);
},
// Override the `save()` method to update the Resource with attributes then
// call the parent dataset and save that. Any `options` provided will be
// passed on to the dataset `save()` method.
save: function (attrs, options) {
var validated = this.set(attrs);
if (validated) {
return this.get('dataset').save({}, options);
}
return validated;
},
// Override the `fetch()` method to call `fetch()` on the parent dataset.
fetch: function (options) {
return this.get('dataset').fetch(options);
},
// Override the `fetch()` method to trigger the `"destroy"` event which
// will remove it from any collections then save the parent dataset.
destroy: function (options) {
return this.trigger('destroy', this).get('dataset').save({}, options);
},
// Override the `toJSON()` method to set the `"package_id"` key required
// by the server.
toJSON: function () {
// Call Backbone.Model rather than Base to break the circular reference.
var obj = Backbone.Model.prototype.toJSON.apply(this, arguments);
if (obj.dataset) {
obj.package_id = obj.dataset.id;
delete obj.dataset;
} else {
obj.package_id = null;
}
return obj;
},
toTemplateJSON: function() {
var obj = Backbone.Model.prototype.toJSON.apply(this, arguments);
obj.displaytitle = obj.description ? obj.description : 'No description ...';
return obj;
},
// Validates the provided attributes. Returns an object literal of
// attribute/error pairs if invalid, `undefined` otherwise.
validate: validator('url')
});
// Helper function that returns a stub method that warns the devloper that
// this method has not yet been implemented.
function apiPlaceholder(method) {
var console = window.console;
return function () {
if (console && console.warn) {
console.warn('The method "' + method + '" has not yet been implemented');
}
return this;
};
}
// A model for working with relationship objects. These are currently just the
// realtionship objects returned by the server wrapped in a `Base` model
// instance. Currently there is no save or delete functionality.
Model.Relationship = Model.Base.extend({
constructor: function Relationship() {
Model.Base.prototype.constructor.apply(this, arguments);
},
// Add placeholder method that simply returns itself to all methods that
// interact with the server. This will also log a warning message to the
// developer into the console.
save: apiPlaceholder('save'),
fetch: apiPlaceholder('fetch'),
destroy: apiPlaceholder('destroy'),
// Validates the provided attributes. Returns an object literal of
// attribute/error pairs if invalid, `undefined` otherwise.
validate: validator('object', 'subject', 'type')
});
// A model for working with relationship objects. These are currently just the
// realtionship objects returned by the server wrapped in a `Base` model
// instance. Currently there is no save or delete functionality.
Model.Group = Model.Base.extend({
constructor: function Group() {
Model.Base.prototype.constructor.apply(this, arguments);
},
toTemplateJSON: function () {
var out = this.toJSON();
var description = this.get('description');
var showdown = new Showdown.converter();
out.descriptionHTML = showdown.makeHtml(description ? description : '');
out.snippet = this.makeSnippet(out.descriptionHTML);
out.dataset_count = this.get('filtered_dataset_count') || this.get('packages').length;
return out;
},
makeSnippet: function (notesHtml) {
var out = $(notesHtml).text();
if (out.length > 190) {
out = out.slice(0, 190) + ' ...';
}
return out;
}
});
Model.GroupCollection = Backbone.Collection.extend({
constructor: function GroupCollection(models, options) {
Backbone.Collection.prototype.constructor.apply(this, arguments);
}
});
// Collection for managing results from the CKAN search API. An additional
// `options.total` parameter can be provided on initialisation to
// indicate how many models there are on the server in total. This can
// then be accessed via the `total` property.
Model.SearchCollection = Backbone.Collection.extend({
constructor: function SearchCollection(models, options) {
if (options) {
this.total = options.total;
}
Backbone.Collection.prototype.constructor.apply(this, arguments);
}
});
return Model;
}(this.jQuery, this._, this.Backbone);
var CKAN = CKAN || {};
CKAN.UI = function($) {
var my = {};
my.Workspace = Backbone.Router.extend({
routes: {
"": "index",
"search/:query/p:page": "search",
"search/:query": "search",
"search": "search",
"dataset/:id/view": "datasetView",
"dataset/:id/edit": "datasetEdit",
"dataset/:datasetId/resource/:resourceId": "resourceView",
"add-dataset": "datasetAdd",
"add-resource": "resourceAdd",
"config": "config"
},
initialize: function(options) {
var self = this;
var defaultConfig = {
endpoint: 'http://ckan.net',
apiKey: ''
};
this.config = options.config || defaultConfig;
this.client = new CKAN.Client(this.config);
if (options.fixtures && options.fixtures.datasets) {
$.each(options.fixtures.datasets, function(idx, obj) {
var collection = self.client.cache.dataset;
collection.add(new CKAN.Model.Dataset(obj));
});
}
var newPkg = this.client.createDataset();
var newCreateView = new CKAN.View.DatasetEditView({model: newPkg, el: $('#dataset-add-page')});
newCreateView.render();
var newResource = new CKAN.Model.Resource({
dataset: newPkg
});
var newResourceEditView = new CKAN.View.ResourceEditView({model: newResource, el: $('#add-resource-page')});
newResourceEditView.render();
this.searchView = new CKAN.View.DatasetSearchView({
client: this.client,
el: $('#search-page')
});
// set up top bar search
$('.search-form').submit(function(e) {
e.preventDefault();
var _el = $(e.target);
var _q = _el.find('input[name="q"]').val();
self.search(_q);
});
var configView = new CKAN.View.ConfigView({
el: $('#config-page'),
config: this.config
});
$(document).bind('config:update', function(e, cfg) {
self.client.configure(cfg);
});
this.notificationView = new CKAN.View.NotificationView({
el: $('.flash-banner-box')
});
},
switchView: function(view) {
$('.page-view').hide();
$('#sidebar .widget-list').empty();
$('#minornavigation').empty();
$('#' + view + '-page').show();
},
index: function(query, page) {
this.switchView("home");
},
search: function(query, page) {
this.searchView.doSearch(query);
this.navigate('search' + '/' + query);
this.switchView('search');
$('.page-heading').html('Search');
},
_findDataset: function(id, callback) {
var pkg = this.client.getDatasetById(id);
if (pkg===undefined) {
pkg = this.client.createDataset({id: id});
pkg.fetch({
success: callback,
error: function() {
alert('There was an error');
}
});
} else {
callback(pkg);
}
},
datasetView: function(id) {
var self = this;
self.switchView('view');
var $viewpage = $('#view-page');
this._findDataset(id, function (model) {
var newView = new CKAN.View.DatasetFullView({
model: model,
el: $viewpage
});
newView.render();
});
},
datasetEdit: function(id) {
this.switchView('dataset-edit');
$('.page-heading').html('Edit Dataset');
function _show(model) {
var newView = new CKAN.View.DatasetEditView({model: model});
$('#dataset-edit-page').html(newView.render().el);
}
this._findDataset(id, _show)
},
datasetAdd: function() {
this.switchView('dataset-add');
$('.page-heading').html('Add Dataset');
$('#sidebar .widget-list').empty();
},
resourceView: function(datasetId, resourceId) {
this.switchView('resource-view');
var $viewpage = $('#resource-view-page');
this._findDataset(datasetId, function (model) {
var resource = model.get('resources').get(resourceId);
var newView = new CKAN.View.ResourceView({
model: resource,
el: $viewpage
});
newView.render();
});
},
resourceAdd: function() {
this.switchView('add-resource');
},
config: function() {
this.switchView('config');
},
url: function(controller, action, id) {
if (id) {
return '#' + controller + '/' + id + '/' + action;
} else {
return '#' + controller + '/' + action;
}
}
});
return my;
}(jQuery);
var CKAN = CKAN || {};
CKAN.View = CKAN.View || {};
(function(my, $) {
my.ConfigView = Backbone.View.extend({
initialize: function() {
this.cfg = {};
this.$ckanUrl = this.el.find('input[name=ckan-url]');
this.$apikey = this.el.find('input[name=ckan-api-key]');
var cfg = this.options.config;
this.$ckanUrl.val(cfg.endpoint);
this.$apikey.val(cfg.apiKey);
},
events: {
'submit #config-form': 'updateConfig'
},
updateConfig: function(e) {
e.preventDefault();
this.saveConfig();
CKAN.View.flash('Saved configuration');
},
saveConfig: function() {
this.cfg = {
'endpoint': this.$ckanUrl.val(),
'apiKey': this.$apikey.val()
};
$.event.trigger('config:update', this.cfg);
}
});
}(CKAN.View, jQuery));
var CKAN = CKAN || {};
CKAN.View = CKAN.View || {};
(function(my, $) {
my.DatasetEditView = Backbone.View.extend({
template: ' \
<form class="dataset" action="" method="POST"> \
<dl> \
<dt> \
<label class="field_opt" for="dataset--title"> \
Title * \
</label> \
</dt> \
<dd> \
<input id="Dataset--title" name="Dataset--title" type="text" value="{{dataset.title}}" placeholder="A title (not a description) ..."/> \
</dd> \
\
<dt> \
<label class="field_req" for="Dataset--name"> \
Name * \
<span class="hints"> \
A short unique name for the dataset - used in urls and restricted to [a-z] -_ \
</span> \
</label> \
</dt> \
<dd> \
<input id="Dataset--name" maxlength="100" name="Dataset--name" type="text" value="{{dataset.name}}" placeholder="A shortish name usable in urls ..." /> \
</dd> \
\
<dt> \
<label class="field_opt" for="Dataset--license_id"> \
Licence \
</label> \
</dt> \
<dd> \
<select id="Dataset--license_id" name="Dataset--license_id"> \
<option selected="selected" value=""></option> \
<option value="notspecified">Other::License Not Specified</option> \
</select> \
</dd> \
\
<dt> \
<label class="field_opt" for="Dataset--notes"> \
Description and Notes \
<span class="hints"> \
(You can use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown formatting</a>) \
</span> \
</label> \
</dt> \
<dd> \
<div class="previewable-textarea"> \
<ul class="tabs"> \
<li><a href="#" action="write" class="selected">Write</a></li> \
<li><a href="#" action="preview">Preview</a></li> \
</ul> \
<textarea id="Dataset--notes" name="Dataset--notes" placeholder="Start with a summary sentence ...">{{dataset.notes}}</textarea> \
<div id="Dataset--notes-preview" class="preview" style="display: none;"> \
<div> \
</div> \
</dd> \
</dl> \
\
<div class="submit"> \
<input id="save" name="save" type="submit" value="Save" /> \
</div> \
</form> \
',
initialize: function() {
_.bindAll(this, 'saveData', 'render');
this.model.bind('change', this.render);
},
render: function() {
tmplData = {
dataset: this.model.toTemplateJSON()
}
var tmpl = Mustache.render(this.template, tmplData);
$(this.el).html(tmpl);
return this;
},
events: {
'submit form.dataset': 'saveData',
'click .previewable-textarea a': 'togglePreview',
'click .dataset-form-navigation a': 'showFormPart'
},
showFormPart: function(e) {
e.preventDefault();
var action = $(e.target)[0].href.split('#')[1];
$('.dataset-form-navigation a').removeClass('selected');
$('.dataset-form-navigation a[href=#' + action + ']').addClass('selected');
},
saveData: function(e) {
e.preventDefault();
this.model.set(this.getData());
this.model.save({}, {
success: function(model) {
CKAN.View.flash('Saved dataset');
window.location.hash = '#dataset/' + model.id + '/view';
},
error: function(model, error) {
CKAN.View.flash('Error saving dataset ' + error.responseText, 'error');
}
});
},
getData: function() {
var _data = $(this.el).find('form.dataset').serializeArray();
modelData = {};
$.each(_data, function(idx, value) {
modelData[value.name.split('--')[1]] = value.value
});
return modelData;
},
togglePreview: function(e) {
// set model data as we use it below for notesHtml
this.model.set(this.getData());
e.preventDefault();
var el = $(e.target);
var action = el.attr('action');
var div = el.closest('.previewable-textarea');
div.find('.tabs a').removeClass('selected');
div.find('.tabs a[action='+action+']').addClass('selected');