Base class for backends providing a template and convenience functions.
You do not have to inherit from this class but even when not it does provide guidance on the functions you must implement.
-
-
Note also that while this (and other Backends) are implemented as Backbone models this is just a convenience.
An implementation of Backbone.sync that will be used to override
Backbone.sync on operations for Datasets and Documents which are using this backend.
-
For read-only implementations you will need only to implement read method
for Dataset models (and even this can be a null operation). The read method
should return relevant metadata for the Dataset. We do not require read support
for Documents because they are loaded in bulk by the query method.
-
For backends supporting write operations you must implement update and delete support for Document objects.
-
-
All code paths should return an object conforming to the jquery promise API.
Query the backend for documents returning them in bulk. This method will
be used by the Dataset.query method to search the backend for documents,
retrieving the results in bulk.
@param {Object} queryObj: object describing a query (usually produced by
using recline.Model.Query and calling toJSON on it).
-
The structure of data in the Query object or
Hash should follow that defined in issue 34.
(Of course, if you are writing your own backend, and hence
have control over the interpretation of the query object, you
can use whatever structure you like).
-
@returns {Promise} promise API object. The promise resolve method will
be called on query completion with a QueryResult object.
-
A QueryResult has the following structure (modelled closely on
ElasticSearch - see this issue for more
details):
-
{
total: // (required) total number of results (can be null)
@@ -68,8 +118,23 @@ details):
// facet results (as per )
}
}
-
Convenience method providing a crude way to catch backend errors on JSONP calls.
Many of backends use JSONP and so will not get error messages and this is
-a crude way to catch those errors.
_wrapInTimeout:function(ourFunction){
+a crude way to catch those errors.
+
+
+
_wrapInTimeout:function(ourFunction){vardfd=$.Deferred();vartimeout=5000;vartimer=setTimeout(function(){
@@ -104,4 +180,9 @@ a crude way to catch those errors.
}(jQuery,this.recline.Backend));
-
\ No newline at end of file
+
+
+
+
+
+
diff --git a/docs/backend/dataproxy.html b/docs/backend/dataproxy.html
index 303d2286..30e64829 100644
--- a/docs/backend/dataproxy.html
+++ b/docs/backend/dataproxy.html
@@ -1,32 +1,72 @@
- dataproxy.js
This should point to the ES type url. E.G. for ES running on
localhost:9200 with index twitter and type tweet it would be
-
-
http://localhost:9200/twitter/tweet
my.ElasticSearch=my.Base.extend({
+
http://localhost:9200/twitter/tweet
+
+
+
my.ElasticSearch=my.Base.extend({_getESUrl:function(dataset){varout=dataset.get('elasticsearch_url');if(out)returnout;
@@ -37,7 +67,19 @@ localhost:9200 with index twitter and type tweet it would be
dataType:'jsonp'});vardfd=$.Deferred();
- this._wrapInTimeout(jqxhr).done(function(schema){
if(out.filters&&out.filters.length){if(!out.filter){
- out.filter={}
+ out.filter={};}if(!out.filter.and){out.filter.and=[];}out.filter.and=out.filter.and.concat(out.filters);}
- if(out.filters!=undefined){
+ if(out.filters!==undefined){deleteout.filters;}returnout;
@@ -97,12 +147,24 @@ localhost:9200 with index twitter and type tweet it would be
data:data,dataType:'jsonp'});
- vardfd=$.Deferred();
jqxhr.done(function(results){_.each(results.hits.hits,function(hit){
- if(!'id'inhit._source&&hit._id){
+ if(!('id'inhit._source)&&hit._id){hit._source.id=hit._id;}
- })
+ });if(results.facets){results.hits.facets=results.facets;}
@@ -115,4 +177,9 @@ localhost:9200 with index twitter and type tweet it would be
}(jQuery,this.recline.Backend));
-
\ No newline at end of file
+
+
+
+
+
+
diff --git a/docs/backend/gdocs.html b/docs/backend/gdocs.html
index 10963ee7..60fba435 100644
--- a/docs/backend/gdocs.html
+++ b/docs/backend/gdocs.html
@@ -1,30 +1,73 @@
- gdocs.js
zip the fields with the data rows to produce js objs
+TODO: factor this out as a common method with other backends
+
+
+
varobjs=_.map(dataset._dataCache,function(d){varobj={};
- _.each(_.zip(fields,d),function(x){obj[x[0]]=x[1];})
+ _.each(_.zip(fields,d),function(x){
+ obj[x[0]]=x[1];
+ });returnobj;});dfd.resolve(this._docsToQueryResult(objs));returndfd;},
- gdocsToJavascript:function(gdocsSpreadsheet){
- /*
- :options: (optional) optional argument dictionary:
- columnsToUse: list of columns to use (specified by field names)
- colTypes: dictionary (with column names as keys) specifying types (e.g. range, percent for use in conversion).
- :return: tabular data object (hash with keys: field and data).
-
- Issues: seems google docs return columns in rows in random order and not even sure whether consistent across rows.
- */
- varoptions={};
+ gdocsToJavascript:function(gdocsSpreadsheet){
:options: (optional) optional argument dictionary:
+ columnsToUse: list of columns to use (specified by field names)
+ colTypes: dictionary (with column names as keys) specifying types (e.g. range, percent for use in conversion).
+ :return: tabular data object (hash with keys: field and data).
+
Issues: seems google docs return columns in rows in random order and not even sure whether consistent across rows.
if(colTypes[col]=='percent'){if(rep.test(value)){varvalue2=rep.exec(value);varvalue3=parseFloat(value2);
@@ -113,4 +262,9 @@ TODO: factor this out as a common method with other backends }(jQuery,this.recline.Backend));
-
\ No newline at end of file
+
+
+
+
+
+
diff --git a/docs/backend/localcsv.html b/docs/backend/localcsv.html
index 1abf5bf3..69dfb80b 100644
--- a/docs/backend/localcsv.html
+++ b/docs/backend/localcsv.html
@@ -1,4 +1,26 @@
- localcsv.js
Converts a Comma Separated Values string into an array of arrays.
Each line in the CSV becomes an array.
-
Empty fields are converted to nulls and non-quoted numbers are converted to integers or floats.
-
@return The CSV parsed as an array
@type Array
-
@param {String} s The string to convert
@param {Boolean} [trm=false] If set to True leading and trailing whitespace is stripped off of each non-quoted field as it is imported
-
Heavily based on uselesscode's JS CSV parser (MIT Licensed):
-thttp://www.uselesscode.org/javascript/csv/
Convenience function to create a simple 'in-memory' dataset in one step.
-
@param data: list of hashes for each document/row in the data ({key:
value, key: value})
@param fields: (optional) list of field hashes (each hash defining a hash
as per recline.Model.Field). If fields not specified they will be taken
from the data.
@param metadata: (optional) dataset metadata - see recline.Model.Dataset.
-If not defined (or id not provided) id will be autogenerated.
my.createDataset=function(data,fields,metadata){
+If not defined (or id not provided) id will be autogenerated.
+
+
+
my.createDataset=function(data,fields,metadata){if(!metadata){
- varmetadata={};
+ metadata={};}if(!metadata.id){metadata.id=String(Math.floor(Math.random()*100000000)+1);
@@ -36,17 +68,22 @@ If not defined (or id not provided) id will be autogenerated.
vardataset=newrecline.Model.Dataset({id:metadata.id},'memory');dataset.fetch();returndataset;
- };
To use it you should provide in your constructor data:
-
metadata (including fields array)
documents: list of hashes, each hash being one doc. A doc must have an id attribute which is unique.
-
Example:
-
// Backend setup
var backend = recline.Backend.Memory();
@@ -65,7 +102,10 @@ If not defined (or id not provided) id will be autogenerated.
var dataset = Dataset({id: 'my-id'}, 'memory');
dataset.fetch();
etc ...
-
my.Memory=my.Base.extend({
+
+
+
+
my.Memory=my.Base.extend({initialize:function(){this.datasets={};},
@@ -74,8 +114,8 @@ If not defined (or id not provided) id will be autogenerated.
},sync:function(method,model,options){varself=this;
+ vardfd=$.Deferred();if(method==="read"){
- vardfd=$.Deferred();if(model.__type__=='Dataset'){varrawDataset=this.datasets[model.id];model.set(rawDataset.metadata);
@@ -85,7 +125,6 @@ If not defined (or id not provided) id will be autogenerated.
}returndfd.promise();}elseif(method==='update'){
- vardfd=$.Deferred();if(model.__type__=='Document'){_.each(self.datasets[model.dataset.id].documents,function(doc,idx){if(doc.id===model.id){
@@ -96,7 +135,6 @@ If not defined (or id not provided) id will be autogenerated.
}returndfd.promise();}elseif(method==='delete'){
- vardfd=$.Deferred();if(model.__type__=='Document'){varrawDataset=self.datasets[model.dataset.id];varnewdocs=_.reject(rawDataset.documents,function(doc){
@@ -121,7 +159,19 @@ If not defined (or id not provided) id will be autogenerated.
varfieldId=_.keys(filter.term)[0];return(doc[fieldId]==filter.term[fieldId]);});
- });
_.each(queryObj.sort,function(sortObj){varfieldName=_.keys(sortObj)[0];results=_.sortBy(results,function(doc){var_out=doc[fieldName];
@@ -145,7 +195,19 @@ If not defined (or id not provided) id will be autogenerated.
_.each(queryObj.facets,function(query,facetId){facetResults[facetId]=newrecline.Model.Facet({id:facetId}).toJSON();facetResults[facetId].termsall={};
- });
_.each(documents,function(doc){_.each(queryObj.facets,function(query,facetId){varfieldId=query.terms.field;varval=doc[fieldId];
@@ -162,7 +224,19 @@ If not defined (or id not provided) id will be autogenerated.
varterms=_.map(tmp.termsall,function(count,term){return{term:term,count:count};});
- tmp.terms=_.sortBy(terms,function(item){
return-item.count;});tmp.terms=tmp.terms.slice(0,10);});
@@ -173,4 +247,9 @@ If not defined (or id not provided) id will be autogenerated.
}(jQuery,this.recline.Backend));
-
A model has the following (non-Backbone) attributes:
-
@property {FieldList} fields: (aka columns) is a FieldList listing all the
fields on this Dataset (this can be set explicitly, or, will be set by
Dataset.fetch() or Dataset.query()
-
@property {DocumentList} currentDocuments: a DocumentList containing the
Documents we have currently loaded for viewing (updated by calling query
method)
-
@property {number} docCount: total number of documents in this dataset
-
@property {Backend} backend: the Backend (instance) for this Dataset
-
@property {Query} queryState: Query object which stores current
queryState. queryState may be edited by other components (e.g. a query
editor view) changes will trigger a Dataset query.
-
@property {FacetList} facets: FacetList object containing all current
-Facets.
format: (optional) used to indicate how the data should be formatted. For example:
-
type=date, format=yyyy-mm-dd
+
format: (optional) used to indicate how the data should be formatted. For example:
+
type=date, format=yyyy-mm-dd
type=float, format=percentage
-
type=float, format='###,###.##'
+
type=float, format='###,###.##'
is_derived: (default: false) attribute indicating this field has no backend data but is just derived from other fields (see below).
-
Following additional instance properties:
-
@property {Function} renderer: a function to render the data for this field.
Signature: function(value, field, doc) where value is the value of this
cell, field is corresponding field object and document is the document
object. Note that implementing functions can ignore arguments (e.g.
function(value) would be a valid formatter function).
-
@property {Function} deriver: a function to derive/compute the value of data
in this field as a function of this field's value (if any) and the current
document, its signature and behaviour is the same as for renderer. Use of
this function allows you to define an entirely new value for data in this
field. This provides support for a) 'derived/computed' fields: i.e. fields
whose data are functions of the data in other fields b) transforming the
-value of this field prior to rendering.
Query instances encapsulate a query to the backend (see query method on backend). Useful both
for creating queries and for storing and manipulating query state -
e.g. from a query editor).
NB: It is up to specific backends how to implement and support this query
structure. Different backends might choose to implement things differently
or not support certain features. Please check your backend for details.
-
Query object has the following key attributes:
-
size (=limit): number of results to return
from (=offset): offset into result set - http://www.elasticsearch.org/guide/reference/api/search/from-size.html
@@ -191,25 +330,26 @@ or not support certain features. Please check your backend for details.
fields: set of fields to return - http://www.elasticsearch.org/guide/reference/api/search/fields.html
-
facets: TODO - see http://www.elasticsearch.org/guide/reference/api/search/facets/
+
facets: specification of facets - see http://www.elasticsearch.org/guide/reference/api/search/facets/
-
Additions:
-
-
q: either straight text or a hash will map directly onto a query_string
-query
-in backend
-
-
Of course this can be re-interpreted by different backends. E.g. some
-may just pass this straight through e.g. for an SQL backend this could be
-the full SQL query
-
filters: dict of ElasticSearch filters. These will be and-ed together for
-execution.
+
+
q: either straight text or a hash will map directly onto a query_string
+ query
+ in backend
+
+
+
Of course this can be re-interpreted by different backends. E.g. some
+ may just pass this straight through e.g. for an SQL backend this could be
+ the full SQL query
+
+
+
filters: dict of ElasticSearch filters. These will be and-ed together for
+ execution.
Specifically the object structure of a facet looks like (there is one
addition compared to ElasticSearch: the "id" field which corresponds to the
key used to specify this facet in the facet query):
-
{
"id": "id-of-facet",
@@ -296,7 +534,10 @@ key used to specify this facet in the facet query):
}
]
}
-
my.Facet=Backbone.Model.extend({
+
+
+
+
my.Facet=Backbone.Model.extend({defaults:function(){return{_type:'terms',
@@ -304,14 +545,42 @@ key used to specify this facet in the facet query):
other:0,missing:0,terms:[]
- }
+ };}
-});
this.model.bind('change',this.render);this.model.fields.bind('reset',this.render);this.model.fields.bind('add',this.render);this.model.currentDocuments.bind('add',this.redraw);
@@ -110,8 +152,32 @@ generate the element itself (you can then append view.el to the DOM.
render:function(){htmls=$.mustache(this.template,this.model.toTemplateJSON());
- $(this.el).html(htmls);
for use later when adding additional series
+could be simpler just to have a common template!
+
+
+
this.$seriesClone=this.el.find('.editor-series').clone();this._updateSeries();returnthis;},
@@ -122,27 +188,71 @@ could be simpler just to have a common template!
The relevant div that graph attaches to his hidden at the moment of creating the plot -- Flot will complain with
+
+
Uncaught Invalid dimensions for plot, width = 0, height = 0
+* There is no data for the plot -- either same error or may have issues later with errors like 'non-existent node-value'
create this.plot and cache it
if (!this.plot) {
this.plot = $.plot(this.$graph, series, options);
} else {
@@ -151,39 +261,90 @@ could be simpler just to have a common template!
TODO: we should really use tickFormatter and 1 interval ticks if (and
only if) x-axis values are non-numeric
However, that is non-trivial to work out from a dataset (datasets may
-have no field type info). Thus at present we only do this for bars.
varoptions={
+have no field type info). Thus at present we only do this for bars.
+
+
+
varoptions={lines:{series:{lines:{show:true}}
- }
- ,points:{
+ },
+ points:{series:{points:{show:true}},grid:{hoverable:true,clickable:true}
- }
- ,'lines-and-points':{
+ },
+ 'lines-and-points':{series:{points:{show:true},lines:{show:true}},grid:{hoverable:true,clickable:true}
- }
- ,bars:{
+ },
+ bars:{series:{lines:{show:false},bars:{
@@ -203,7 +364,7 @@ have no field type info). Thus at present we only do this for bars.
max:self.model.currentDocuments.length-0.5}}
- }
+ };returnoptions[typeId];},
@@ -230,7 +391,19 @@ have no field type info). Thus at present we only do this for bars.
$("#flot-tooltip").remove();varx=item.datapoint[0];
- vary=item.datapoint[1];
convert back from 'index' value on x-axis (e.g. in cases where non-number values)
+
+
+
if(self.model.currentDocuments.models[x]){x=self.model.currentDocuments.models[x].get(self.chartConfig.group);}else{x=x.toFixed(2);
@@ -264,7 +437,19 @@ have no field type info). Thus at present we only do this for bars.
vary=doc.get(field);if(typeofx==='string'){x=index;
- }
if(self.chartConfig.graphType=='bars'){points.push([y,x]);}else{points.push([x,y]);
@@ -274,12 +459,22 @@ have no field type info). Thus at present we only do this for bars.
});}returnseries;
- },
TODO: delete or re-enable (currently this code is not used from anywhere except deprecated or disabled methods (see above)).
+ 'click .column-header-menu':'onColumnHeaderClick',
+ 'click .row-header-menu':'onRowHeaderClick',
+ 'click .root-header-menu':'onRootHeaderClick',
+ 'click .data-table-menu li a':'onMenuClick'
+ },
+
+
+
TODO: delete or re-enable (currently this code is not used from anywhere except deprecated or disabled methods (see above)).
showDialog: function(template, data) {
if (!data) data = {};
util.show('dialog');
@@ -36,8 +75,24 @@ showDialog: function(template, data) {
util.hide('dialog');
})
$('.dialog').draggable({ handle: '.dialog-header', cursor: 'move' });
-},
important this is == as the currentRow will be string (as comes
+from DOM) while id may be int
+
+
+
returndoc.id==self.state.currentRow;});doc.destroy().then(function(){self.model.currentDocuments.remove(doc);my.notify("Row deleted successfully");
- })
- .fail(function(err){
- my.notify("Errorz! "+err)
- })
+ }).fail(function(err){
+ my.notify("Errorz! "+err);
+ });}
- }
+ };actions[$(e.target).attr('data-action')]();},
@@ -98,7 +167,7 @@ from DOM) while id may be int
$el.append(view.el);util.observeExit($el,function(){util.hide('dialog');
- })
+ });$('.dialog').draggable({handle:'.dialog-header',cursor:'move'});},
@@ -112,7 +181,7 @@ from DOM) while id may be int
$el.append(view.el);util.observeExit($el,function(){util.hide('dialog');
- })
+ });$('.dialog').draggable({handle:'.dialog-header',cursor:'move'});},
@@ -130,9 +199,21 @@ from DOM) while id may be int
template:' \ <table class="recline-grid table-striped table-condensed" cellspacing="0"> \ <thead> \ <tr> \
@@ -151,7 +232,8 @@ from DOM) while id may be int
<div class="btn-group column-header-menu"> \
<a class="btn dropdown-toggle" data-toggle="dropdown"><i class="icon-cog"></i><span class="caret"></span></a> \ <ul class="dropdown-menu data-table-menu pull-right"> \
- <li><a data-action="facet" href="JavaScript:void(0);">Facet on this Field</a></li> \
+ <li><a data-action="facet" href="JavaScript:void(0);">Term Facet</a></li> \
+ <li><a data-action="facet_histogram" href="JavaScript:void(0);">Date Histogram Facet</a></li> \ <li><a data-action="filter" href="JavaScript:void(0);">Text Filter</a></li> \ <li class="divider"></li> \ <li><a data-action="sortAsc" href="JavaScript:void(0);">Sort ascending</a></li> \
@@ -172,8 +254,20 @@ from DOM) while id may be int
TODO: move this sort of thing into a toTemplateJSON method on Dataset?
+
+
+
modelData.fields=_.map(this.fields,function(field){returnfield.toJSON();});returnmodelData;},render:function(){
@@ -193,24 +287,32 @@ from DOM) while id may be int
Map view for a Dataset using Leaflet mapping library.
+
This view allows to plot gereferenced documents on a map. The location
+information can be provided either via a field with
+GeoJSON objects or two fields with latitude and
+longitude coordinates.
+
Initialization arguments:
+
+
+
options: initial options. They must contain a model:
For each document passed, a GeoJSON geometry will be extracted and added
+to the features layer. If an exception is thrown, the process will be
+stopped and an error notification shown.
+
Each feature will have a popup associated with all the document fields.
The primary view for the entire application. Usage:
-
var myExplorer = new model.recline.DataExplorer({
model: {{recline.Model.Dataset instance}}
@@ -13,18 +41,14 @@ var myExplorer = new model.recline.DataExplorer({
views: {{page views}}
config: {{config options -- see below}}
});
-
+
Parameters
-
model: (required) Dataset instance.
-
el: (required) DOM element.
-
views: (optional) the views (Grid, Graph etc) for DataExplorer to
show. This is an array of view hashes. If not provided
just initialize a DataGrid with id 'grid'. Example:
-
var views = [
{
@@ -45,14 +69,15 @@ var views = [
config: Config options like:
-
readOnly: true/false (default: false) value indicating whether to
-operate in read-only mode (hiding all editing options).
+ operate in read-only mode (hiding all editing options).
-
NB: the element already being in the DOM is important for rendering of
-FlotGraph subview.
retrieve basic data like fields etc
+note this.model and dataset returned are the same
+
+
+
this.model.fetch().done(function(dataset){varqueryState=my.parseHashQueryString().reclineQuery;if(queryState){
@@ -163,7 +236,7 @@ note this.model and dataset returned are the same
$(this.el).html(template);var$dataViewContainer=this.el.find('.data-view-container');_.each(this.pageViews,function(view,pageName){
- $dataViewContainer.append(view.view.el)
+ $dataViewContainer.append(view.view.el);});varqueryEditor=newmy.QueryEditor({model:this.model.queryState
@@ -182,7 +255,19 @@ note this.model and dataset returned are the same
},setupRouting:function(){
- varself=this;
this.router.route(/^(\?.*)?$/,this.pageViews[0].id,function(queryString){self.updateNav(self.pageViews[0].id,queryString);});$.each(this.pageViews,function(idx,view){
@@ -197,11 +282,25 @@ note this.model and dataset returned are the same
this.el.find('.navigation li a').removeClass('disabled');var$el=this.el.find('.navigation li a[href=#'+pageName+']');$el.parent().addClass('active');
- $el.addClass('disabled');
_.each(this.pageViews,function(view,idx){if(view.id===pageName){view.view.el.show();
+ view.view.trigger('view:show');}else{view.view.el.hide();
+ view.view.trigger('view:hide');}});},
@@ -237,8 +336,8 @@ note this.model and dataset returned are the same
',events:{
- 'submit form':'onFormSubmit'
- ,'click .action-pagination-update':'onPaginationUpdate'
+ 'submit form':'onFormSubmit',
+ 'click .action-pagination-update':'onPaginationUpdate'},initialize:function(){
@@ -257,10 +356,11 @@ note this.model and dataset returned are the same
onPaginationUpdate:function(e){e.preventDefault();var$el=$(e.target);
+ varnewFrom=0;if($el.parent().hasClass('prev')){
- varnewFrom=this.model.get('from')-Math.max(0,this.model.get('size'));
+ newFrom=this.model.get('from')-Math.max(0,this.model.get('size'));}else{
- varnewFrom=this.model.get('from')+this.model.get('size');
+ newFrom=this.model.get('from')+this.model.get('size');}this.model.set({from:newFrom});},
@@ -317,7 +417,19 @@ note this.model and dataset returned are the same
this.render();},render:function(){
- vartmplData=$.extend(true,{},this.model.toJSON());
tmplData.filters=_.map(tmplData.filters,function(filter,idx){filter.id=idx;returnfilter;});
@@ -331,10 +443,22 @@ note this.model and dataset returned are the same
my.composeQueryString=function(queryParams){varqueryString='?';varitems=[];$.each(queryParams,function(key,value){
@@ -460,35 +678,57 @@ note this.model and dataset returned are the same
+
+
+
+
+
diff --git a/index.html b/index.html
index e7b7d616..1db10c36 100644
--- a/index.html
+++ b/index.html
@@ -254,7 +254,7 @@ also easily write your own). Each view holds a pointer to a Dataset:
\
@@ -1124,10 +1153,10 @@ my.DataGrid = Backbone.View.extend({
',
toTemplateJSON: function() {
- var modelData = this.model.toJSON()
- modelData.notEmpty = ( this.fields.length > 0 )
+ var modelData = this.model.toJSON();
+ modelData.notEmpty = ( this.fields.length > 0 );
// TODO: move this sort of thing into a toTemplateJSON method on Dataset?
- modelData.fields = _.map(this.fields, function(field) { return field.toJSON() });
+ modelData.fields = _.map(this.fields, function(field) { return field.toJSON(); });
return modelData;
},
render: function() {
@@ -1147,7 +1176,7 @@ my.DataGrid = Backbone.View.extend({
});
newView.render();
});
- this.el.toggleClass('no-hidden', (self.hiddenFields.length == 0));
+ this.el.toggleClass('no-hidden', (self.hiddenFields.length === 0));
return this;
}
});
@@ -1206,9 +1235,9 @@ my.DataGridRow = Backbone.View.extend({
return {
field: field.id,
value: doc.getFieldValue(field)
- }
- })
- return { id: this.id, cells: cellData }
+ };
+ });
+ return { id: this.id, cells: cellData };
},
render: function() {
@@ -1265,52 +1294,151 @@ this.recline.View = this.recline.View || {};
(function($, my) {
+// ## Map view for a Dataset using Leaflet mapping library.
+//
+// This view allows to plot gereferenced documents on a map. The location
+// information can be provided either via a field with
+// [GeoJSON](http://geojson.org) objects or two fields with latitude and
+// longitude coordinates.
+//
+// Initialization arguments:
+//
+// * options: initial options. They must contain a model:
+//
+// {
+// model: {recline.Model.Dataset}
+// }
+//
+// * config: (optional) map configuration hash (not yet used)
+//
+//
my.Map = Backbone.View.extend({
tagName: 'div',
className: 'data-map-container',
- latitudeFieldNames: ['lat','latitude'],
- longitudeFieldNames: ['lon','longitude'],
- geometryFieldNames: ['geom','the_geom','geometry','spatial'],
-
- //TODO: In case we want to change the default markers
- /*
- markerOptions: {
- radius: 5,
- color: 'grey',
- fillColor: 'orange',
- weight: 2,
- opacity: 1,
- fillOpacity: 1
- },
- */
-
template: ' \
+
\
+
\
+ \
+
\
\
\
',
+ // These are the default field names that will be used if found.
+ // If not found, the user will need to define the fields via the editor.
+ latitudeFieldNames: ['lat','latitude'],
+ longitudeFieldNames: ['lon','longitude'],
+ geometryFieldNames: ['geom','the_geom','geometry','spatial','location'],
+
+ // Define here events for UI elements
+ events: {
+ 'click .editor-update-map': 'onEditorSubmit',
+ 'change .editor-field-type': 'onFieldTypeChange'
+ },
+
+
initialize: function(options, config) {
var self = this;
this.el = $(this.el);
- this.render();
+
+ // Listen to changes in the fields
this.model.bind('change', function() {
self._setupGeometryField();
});
+ this.model.fields.bind('add', this.render);
+ this.model.fields.bind('reset', function(){
+ self._setupGeometryField()
+ self.render()
+ });
+
+ // Listen to changes in the documents
+ this.model.currentDocuments.bind('add', function(doc){self.redraw('add',doc)});
+ this.model.currentDocuments.bind('remove', function(doc){self.redraw('remove',doc)});
+ this.model.currentDocuments.bind('reset', function(){self.redraw('reset')});
+
+ // If the div was hidden, Leaflet needs to recalculate some sizes
+ // to display properly
+ this.bind('view:show',function(){
+ self.map.invalidateSize();
+ });
this.mapReady = false;
+
+ this.render();
},
+ // Public: Adds the necessary elements to the page.
+ //
+ // Also sets up the editor fields and the map if necessary.
render: function() {
var self = this;
htmls = $.mustache(this.template, this.model.toTemplateJSON());
+
$(this.el).html(htmls);
this.$map = this.el.find('.panel.map');
+ if (this.geomReady && this.model.fields.length){
+ if (this._geomFieldName){
+ this._selectOption('editor-geom-field',this._geomFieldName);
+ $('#editor-field-type-geom').attr('checked','checked').change();
+ } else{
+ this._selectOption('editor-lon-field',this._lonFieldName);
+ this._selectOption('editor-lat-field',this._latFieldName);
+ $('#editor-field-type-latlon').attr('checked','checked').change();
+ }
+ }
+
this.model.bind('query:done', function() {
if (!self.geomReady){
self._setupGeometryField();
@@ -1319,41 +1447,143 @@ my.Map = Backbone.View.extend({
if (!self.mapReady){
self._setupMap();
}
- self.redraw()
+ self.redraw();
});
return this;
},
- redraw: function(){
+ // Public: Redraws the features on the map according to the action provided
+ //
+ // Actions can be:
+ //
+ // * reset: Clear all features
+ // * add: Add one or n features (documents)
+ // * remove: Remove one or n features (documents)
+ // * refresh: Clear existing features and add all current documents
+ //
+ redraw: function(action,doc){
var self = this;
- if (this.geomReady){
- if (this.model.currentDocuments.length > 0){
+ action = action || 'refresh';
+
+ if (this.geomReady && this.mapReady){
+ if (action == 'reset'){
this.features.clearLayers();
- var bounds = new L.LatLngBounds();
-
- this.model.currentDocuments.forEach(function(doc){
- var feature = self._getGeometryFromDocument(doc);
- if (feature){
- // Build popup contents
- // TODO: mustache?
- html = ''
- for (key in doc.attributes){
- html += '
' + key + ': '+ doc.attributes[key] + '
'
- }
- feature.properties = {popupContent: html};
-
- self.features.addGeoJSON(feature);
-
- // TODO: bounds and center map
- }
- });
+ } else if (action == 'add' && doc){
+ this._add(doc);
+ } else if (action == 'remove' && doc){
+ this._remove(doc);
+ } else if (action == 'refresh'){
+ this.features.clearLayers();
+ this._add(this.model.currentDocuments.models);
}
}
},
+ //
+ // UI Event handlers
+ //
+
+ // Public: Update map with user options
+ //
+ // Right now the only configurable option is what field(s) contains the
+ // location information.
+ //
+ onEditorSubmit: function(e){
+ e.preventDefault();
+ if ($('#editor-field-type-geom').attr('checked')){
+ this._geomFieldName = $('.editor-geom-field > select > option:selected').val();
+ this._latFieldName = this._lonFieldName = false;
+ } else {
+ this._geomFieldName = false;
+ this._latFieldName = $('.editor-lat-field > select > option:selected').val();
+ this._lonFieldName = $('.editor-lon-field > select > option:selected').val();
+ }
+ this.geomReady = (this._geomFieldName || (this._latFieldName && this._lonFieldName));
+ this.redraw();
+
+ return false;
+ },
+
+ // Public: Shows the relevant select lists depending on the location field
+ // type selected.
+ //
+ onFieldTypeChange: function(e){
+ if (e.target.value == 'geom'){
+ $('.editor-field-type-geom').show();
+ $('.editor-field-type-latlon').hide();
+ } else {
+ $('.editor-field-type-geom').hide();
+ $('.editor-field-type-latlon').show();
+ }
+ },
+
+ // Private: Add one or n features to the map
+ //
+ // For each document passed, a GeoJSON geometry will be extracted and added
+ // to the features layer. If an exception is thrown, the process will be
+ // stopped and an error notification shown.
+ //
+ // Each feature will have a popup associated with all the document fields.
+ //
+ _add: function(doc){
+
+ var self = this;
+
+ if (!(doc instanceof Array)) doc = [doc];
+
+ doc.forEach(function(doc){
+ var feature = self._getGeometryFromDocument(doc);
+ if (feature instanceof Object){
+ // Build popup contents
+ // TODO: mustache?
+ html = ''
+ for (key in doc.attributes){
+ html += '
diff --git a/src/view-grid.js b/src/view-grid.js
index 02082455..cb959f18 100644
--- a/src/view-grid.js
+++ b/src/view-grid.js
@@ -4,12 +4,12 @@ this.recline = this.recline || {};
this.recline.View = this.recline.View || {};
(function($, my) {
-// ## DataGrid
+// ## (Data) Grid Dataset View
//
// Provides a tabular view on a Dataset.
//
// Initialize it with a `recline.Model.Dataset`.
-my.DataGrid = Backbone.View.extend({
+my.Grid = Backbone.View.extend({
tagName: "div",
className: "recline-grid-container",
@@ -211,7 +211,7 @@ my.DataGrid = Backbone.View.extend({
this.model.currentDocuments.forEach(function(doc) {
var tr = $('
');
self.el.find('tbody').append(tr);
- var newView = new my.DataGridRow({
+ var newView = new my.GridRow({
model: doc,
el: tr,
fields: self.fields
@@ -223,22 +223,22 @@ my.DataGrid = Backbone.View.extend({
}
});
-// ## DataGridRow View for rendering an individual document.
+// ## GridRow View for rendering an individual document.
//
// Since we want this to update in place it is up to creator to provider the element to attach to.
//
-// In addition you *must* pass in a FieldList in the constructor options. This should be list of fields for the DataGrid.
+// In addition you *must* pass in a FieldList in the constructor options. This should be list of fields for the Grid.
//
// Example:
//
//
-// var row = new DataGridRow({
+// var row = new GridRow({
// model: dataset-document,
// el: dom-element,
// fields: mydatasets.fields // a FieldList object
// });
//
-my.DataGridRow = Backbone.View.extend({
+my.GridRow = Backbone.View.extend({
initialize: function(initData) {
_.bindAll(this, 'render');
this._fields = initData.fields;
diff --git a/src/view.js b/src/view.js
index 368bc95b..b78e1901 100644
--- a/src/view.js
+++ b/src/view.js
@@ -38,14 +38,14 @@ this.recline.View = this.recline.View || {};
//
// **views**: (optional) the dataset views (Grid, Graph etc) for
// DataExplorer to show. This is an array of view hashes. If not provided
-// just initialize a DataGrid with id 'grid'. Example:
+// just initialize a Grid with id 'grid'. Example:
//
//
// var views = [
// {
// id: 'grid', // used for routing
// label: 'Grid', // used for view switcher
-// view: new recline.View.DataGrid({
+// view: new recline.View.Grid({
// model: dataset
// })
// },
@@ -107,7 +107,7 @@ my.DataExplorer = Backbone.View.extend({
this.pageViews = [{
id: 'grid',
label: 'Grid',
- view: new my.DataGrid({
+ view: new my.Grid({
model: this.model
})
}];
diff --git a/test/view-grid.test.js b/test/view-grid.test.js
index 750cca2a..b415acde 100644
--- a/test/view-grid.test.js
+++ b/test/view-grid.test.js
@@ -1,10 +1,10 @@
(function ($) {
-module("View - DataGrid");
+module("View - Grid");
test('menu - hideColumn', function () {
var dataset = Fixture.getDataset();
- var view = new recline.View.DataGrid({
+ var view = new recline.View.Grid({
model: dataset
});
$('.fixtures .test-datatable').append(view.el);
@@ -22,7 +22,7 @@ test('menu - hideColumn', function () {
test('state', function () {
var dataset = Fixture.getDataset();
- var view = new recline.View.DataGrid({
+ var view = new recline.View.Grid({
model: dataset,
state: {
hiddenFields: ['z']
@@ -35,7 +35,7 @@ test('state', function () {
view.remove();
});
-test('new DataGridRow View', function () {
+test('new GridRow View', function () {
var $el = $('
\
From 2515658a0b9ed1093b74a1d3cb87d98f4ee712b0 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 17:00:42 +0100
Subject: [PATCH 32/48] [#80,refactor][xs]: switch to _.each in view-graph.js.
---
src/view-graph.js | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/view-graph.js b/src/view-graph.js
index 0bfbd007..08695a92 100644
--- a/src/view-graph.js
+++ b/src/view-graph.js
@@ -275,9 +275,9 @@ my.Graph = Backbone.View.extend({
createSeries: function () {
var self = this;
var series = [];
- $.each(this.state.attributes.series, function (seriesIndex, field) {
+ _.each(this.state.attributes.series, function(field) {
var points = [];
- $.each(self.model.currentDocuments.models, function (index, doc) {
+ _.each(self.model.currentDocuments.models, function(doc, index) {
var x = doc.get(self.state.attributes.group);
var y = doc.get(field);
if (typeof x === 'string') {
From 270f68784c83247a7481fa28ea9de8d4c167382c Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 17:07:43 +0100
Subject: [PATCH 33/48] [#81,css][xs]: css class read-only ->
recline-read-only.
---
css/grid.css | 16 ++++++++--------
src/view.js | 2 +-
2 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/css/grid.css b/css/grid.css
index fd525be6..4e4bd806 100644
--- a/css/grid.css
+++ b/css/grid.css
@@ -63,10 +63,6 @@
float: right;
}
-.read-only a.row-header-menu {
- display: none;
-}
-
div.data-table-cell-content {
line-height: 1.2;
color: #222;
@@ -301,15 +297,19 @@ td.expression-preview-value {
* Read-only mode
*********************************************************/
-.read-only .no-hidden .recline-grid tr td:first-child,
-.read-only .no-hidden .recline-grid tr th:first-child
+.recline-read-only .no-hidden .recline-grid tr td:first-child,
+.recline-read-only .no-hidden .recline-grid tr th:first-child
{
display: none;
}
-.read-only .recline-grid .write-op,
-.read-only .recline-grid a.data-table-cell-edit
+.recline-read-only .recline-grid .write-op,
+.recline-read-only .recline-grid a.data-table-cell-edit
{
display: none;
}
+.recline-read-only a.row-header-menu {
+ display: none;
+}
+
diff --git a/src/view.js b/src/view.js
index b78e1901..815af453 100644
--- a/src/view.js
+++ b/src/view.js
@@ -163,7 +163,7 @@ my.DataExplorer = Backbone.View.extend({
},
setReadOnly: function() {
- this.el.addClass('read-only');
+ this.el.addClass('recline-read-only');
},
render: function() {
From d71203e69a5d8db3273a6e861c842e73303069f4 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 17:29:29 +0100
Subject: [PATCH 34/48] [#88,refactor/state][s]: map view now supports state
(used for specifying geometry/lat/lon fields).
---
src/view-map.js | 85 +++++++++++++++++++++++++++----------------------
1 file changed, 47 insertions(+), 38 deletions(-)
diff --git a/src/view-map.js b/src/view-map.js
index 8c9123fd..6759c55e 100644
--- a/src/view-map.js
+++ b/src/view-map.js
@@ -12,17 +12,17 @@ this.recline.View = this.recline.View || {};
// [GeoJSON](http://geojson.org) objects or two fields with latitude and
// longitude coordinates.
//
-// Initialization arguments:
-//
-// * options: initial options. They must contain a model:
-//
-// {
-// model: {recline.Model.Dataset}
-// }
-//
-// * config: (optional) map configuration hash (not yet used)
-//
+// Initialization arguments are as standard for Dataset Views. State object may
+// have the following (optional) configuration options:
//
+//
+// {
+// // geomField if specified will be used in preference to lat/lon
+// geomField: {id of field containing geometry in the dataset}
+// lonField: {id of field containing longitude in the dataset}
+// latField: {id of field containing latitude in the dataset}
+// }
+//
my.Map = Backbone.View.extend({
tagName: 'div',
@@ -95,14 +95,12 @@ my.Map = Backbone.View.extend({
'change .editor-field-type': 'onFieldTypeChange'
},
-
- initialize: function(options, config) {
+ initialize: function(options) {
var self = this;
-
this.el = $(this.el);
// Listen to changes in the fields
- this.model.bind('change', function() {
+ this.model.fields.bind('change', function() {
self._setupGeometryField();
});
this.model.fields.bind('add', this.render);
@@ -122,8 +120,16 @@ my.Map = Backbone.View.extend({
self.map.invalidateSize();
});
- this.mapReady = false;
+ var stateData = _.extend({
+ geomField: null,
+ lonField: null,
+ latField: null
+ },
+ options.state
+ );
+ this.state = new recline.Model.ObjectState(stateData);
+ this.mapReady = false;
this.render();
},
@@ -140,12 +146,12 @@ my.Map = Backbone.View.extend({
this.$map = this.el.find('.panel.map');
if (this.geomReady && this.model.fields.length){
- if (this._geomFieldName){
- this._selectOption('editor-geom-field',this._geomFieldName);
+ if (this.state.get('geomField')){
+ this._selectOption('editor-geom-field',this.state.get('geomField'));
$('#editor-field-type-geom').attr('checked','checked').change();
} else{
- this._selectOption('editor-lon-field',this._lonFieldName);
- this._selectOption('editor-lat-field',this._latFieldName);
+ this._selectOption('editor-lon-field',this.state.get('lonField'));
+ this._selectOption('editor-lat-field',this.state.get('latField'));
$('#editor-field-type-latlon').attr('checked','checked').change();
}
}
@@ -174,9 +180,7 @@ my.Map = Backbone.View.extend({
// * refresh: Clear existing features and add all current documents
//
redraw: function(action,doc){
-
var self = this;
-
action = action || 'refresh';
if (this.geomReady && this.mapReady){
@@ -205,14 +209,19 @@ my.Map = Backbone.View.extend({
onEditorSubmit: function(e){
e.preventDefault();
if ($('#editor-field-type-geom').attr('checked')){
- this._geomFieldName = $('.editor-geom-field > select > option:selected').val();
- this._latFieldName = this._lonFieldName = false;
+ this.state.set({
+ geomField: $('.editor-geom-field > select > option:selected').val(),
+ lonField: null,
+ latField: null
+ });
} else {
- this._geomFieldName = false;
- this._latFieldName = $('.editor-lat-field > select > option:selected').val();
- this._lonFieldName = $('.editor-lon-field > select > option:selected').val();
+ this.state.set({
+ geomField: null,
+ lonField: $('.editor-lon-field > select > option:selected').val(),
+ latField: $('.editor-lat-field > select > option:selected').val()
+ });
}
- this.geomReady = (this._geomFieldName || (this._latFieldName && this._lonFieldName));
+ this.geomReady = (this.state.get('geomField') || (this.state.get('latField') && this.state.get('lonField')));
this.redraw();
return false;
@@ -301,16 +310,16 @@ my.Map = Backbone.View.extend({
//
_getGeometryFromDocument: function(doc){
if (this.geomReady){
- if (this._geomFieldName){
+ if (this.state.get('geomField')){
// We assume that the contents of the field are a valid GeoJSON object
- return doc.attributes[this._geomFieldName];
- } else if (this._lonFieldName && this._latFieldName){
+ return doc.attributes[this.state.get('geomField')];
+ } else if (this.state.get('lonField') && this.state.get('latField')){
// We'll create a GeoJSON like point object from the two lat/lon fields
return {
type: 'Point',
coordinates: [
- doc.attributes[this._lonFieldName],
- doc.attributes[this._latFieldName]
+ doc.attributes[this.state.get('lonField')],
+ doc.attributes[this.state.get('latField')]
]
};
}
@@ -324,12 +333,12 @@ my.Map = Backbone.View.extend({
// If not found, the user can define them via the UI form.
_setupGeometryField: function(){
var geomField, latField, lonField;
-
- this._geomFieldName = this._checkField(this.geometryFieldNames);
- this._latFieldName = this._checkField(this.latitudeFieldNames);
- this._lonFieldName = this._checkField(this.longitudeFieldNames);
-
- this.geomReady = (this._geomFieldName || (this._latFieldName && this._lonFieldName));
+ this.state.set({
+ geomField: this._checkField(this.geometryFieldNames),
+ latField: this._checkField(this.latitudeFieldNames),
+ lonField: this._checkField(this.longitudeFieldNames)
+ });
+ this.geomReady = (this.state.get('geomField') || (this.state.get('latField') && this.state.get('lonField')));
},
// Private: Check if a field in the current model exists in the provided
From 002308f78f455907867448f306c32bdab5b3b744 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 18:49:07 +0100
Subject: [PATCH 35/48] [#88,doc/view][m]: document state concept and usage
plus provide general overview of recline views and how Dataset Views should
be structured.
---
src/view.js | 97 ++++++++++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 88 insertions(+), 9 deletions(-)
diff --git a/src/view.js b/src/view.js
index 815af453..0b46df21 100644
--- a/src/view.js
+++ b/src/view.js
@@ -1,16 +1,83 @@
/*jshint multistr:true */
-// # Core View Functionality plus Data Explorer
+// # Recline Views
//
-// ## Common view concepts
+// Recline Views are Backbone Views and in keeping with normal Backbone views
+// are Widgets / Components displaying something in the DOM. Like all Backbone
+// views they have a pointer to a model or a collection and is bound to an
+// element.
+//
+// Views provided by core Recline are crudely divided into two types:
+//
+// * Dataset Views: a View intended for displaying a recline.Model.Dataset
+// in some fashion. Examples are the Grid, Graph and Map views.
+// * Widget Views: a widget used for displaying some specific (and
+// smaller) aspect of a dataset or the application. Examples are
+// QueryEditor and FilterEditor which both provide a way for editing (a
+// part of) a `recline.Model.Query` associated to a Dataset.
+//
+// ## Dataset View
+//
+// These views are just Backbone views with a few additional conventions:
+//
+// 1. The model passed to the View should always be a recline.Model.Dataset instance
+// 2. Views should generate their own root element rather than having it passed
+// in.
+// 3. Views should apply a css class named 'recline-{view-name-lower-cased} to
+// the root element (and for all CSS for this view to be qualified using this
+// CSS class)
+// 4. Read-only mode: CSS for this view should respect/utilize
+// recline-read-only class to trigger read-only behaviour (this class will
+// usually be set on some parent element of the view's root element.
+// 5. State: state (configuration) information for the view should be stored on
+// an attribute named state that is an instance of a Backbone Model (or, more
+// speficially, be an instance of `recline.Model.ObjectState`). In addition,
+// a state attribute may be specified in the Hash passed to a View on
+// iniitialization and this information should be used to set the initial
+// state of the view.
+//
+// Example of state would be the set of fields being plotted in a graph
+// view.
+//
+// More information about State can be found below.
+//
+// To summarize some of this, the initialize function for a Dataset View should
+// look like:
+//
+//
//
// ### State
//
-// TODO
+// State information exists in order to support state serialization into the
+// url or elsewhere and reloading of application from a stored state.
//
-// ### Read-only
+// State is available not only for individual views (as described above) but
+// for the dataset (e.g. the current query). For an example of pulling together
+// state from across multiple components see `recline.View.DataExplorer`.
+//
+// ### Writing your own Views
//
-// TODO
+// See the existing Views.
+//
+// ----
+
+// Standard JS module setup
this.recline = this.recline || {};
this.recline.View = this.recline.View || {};
@@ -59,10 +126,20 @@ this.recline.View = this.recline.View || {};
// ];
//
//
-// **state**: state config for this view. Options are:
+// **state**: standard state config for this view. This state is slightly
+// special as it includes config of many of the subviews.
//
-// * readOnly: true/false (default: false) value indicating whether to
-// operate in read-only mode (hiding all editing options).
+//
+// state = {
+// query: {dataset query state - see dataset.queryState object}
+// view-{id1}: {view-state for this view}
+// view-{id2}: {view-state for }
+// ...
+// // Explorer
+// currentView: id of current view (defaults to first view if not specified)
+// readOnly: (default: false) run in read-only mode
+// }
+//
\
@@ -278,7 +355,9 @@ my.DataExplorer = Backbone.View.extend({
});
},
- // Get the current state of dataset and views
+ // ### getState
+ //
+ // Get the current state of dataset and views (see discussion of state above)
getState: function() {
return this.state;
}
From 7743534eac6673c9dc942f0912d194e6cdc64215 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 22:19:43 +0100
Subject: [PATCH 36/48] [#88,backend][s]: add __type__ attribute to all
backends to identify them and provide a more robust and generic way to load
backends from a string identifier such as that __type__ field.
* Also remove recline.Model.backends registry as can be replaced with this more generic solution.
* This refactoring is necessitated by our need to serialize backend info for save/reload of a dataset and explorer state in #88.
---
index.html | 10 ++-----
src/backend/base.js | 12 +++++++-
src/backend/dataproxy.js | 3 +-
src/backend/elasticsearch.js | 2 +-
src/backend/gdocs.js | 2 +-
src/backend/memory.js | 6 ++--
src/model.js | 45 ++++++++++++++++++++++++++++--
test/backend.elasticsearch.test.js | 3 +-
test/backend.test.js | 8 ++++--
test/index.html | 2 +-
test/model.test.js | 10 +++++++
11 files changed, 80 insertions(+), 23 deletions(-)
diff --git a/index.html b/index.html
index 30c80bf8..db4c4b93 100644
--- a/index.html
+++ b/index.html
@@ -182,13 +182,9 @@ Backbone.history.start();
Creating a Dataset Explicitly with a Backend
-// Backend can be an instance or string id for a backend in the
-// recline.Model.backends registry
-var backend = 'elasticsearch'
-// alternatively you can create explicitly
-// var backend = new recline.Backend.ElasticSearch();
-// or even from your own backend ...
-// var backend = new myModule.Backend();
+// Connect to ElasticSearch index/type as our data source
+// There are many other backends you can use (and you can write your own)
+var backend = new recline.Backend.ElasticSearch();
// Dataset is a Backbone model so the first hash become model attributes
var dataset = recline.Model.Dataset({
diff --git a/src/backend/base.js b/src/backend/base.js
index ec4d8412..e9c4eea7 100644
--- a/src/backend/base.js
+++ b/src/backend/base.js
@@ -17,10 +17,20 @@ this.recline.Backend = this.recline.Backend || {};
// ## recline.Backend.Base
//
// Base class for backends providing a template and convenience functions.
- // You do not have to inherit from this class but even when not it does provide guidance on the functions you must implement.
+ // You do not have to inherit from this class but even when not it does
+ // provide guidance on the functions you must implement.
//
// Note also that while this (and other Backends) are implemented as Backbone models this is just a convenience.
my.Base = Backbone.Model.extend({
+ // ### __type__
+ //
+ // 'type' of this backend. This should be either the class path for this
+ // object as a string (e.g. recline.Backend.Memory) or for Backends within
+ // recline.Backend module it may be their class name.
+ //
+ // This value is used as an identifier for this backend when initializing
+ // backends (see recline.Model.Dataset.initialize).
+ __type__: 'base',
// ### sync
//
diff --git a/src/backend/dataproxy.js b/src/backend/dataproxy.js
index 794b8e79..8f2b7496 100644
--- a/src/backend/dataproxy.js
+++ b/src/backend/dataproxy.js
@@ -17,6 +17,7 @@ this.recline.Backend = this.recline.Backend || {};
//
// Note that this is a **read-only** backend.
my.DataProxy = my.Base.extend({
+ __type__: 'dataproxy',
defaults: {
dataproxy_url: 'http://jsonpdataproxy.appspot.com'
},
@@ -71,7 +72,5 @@ this.recline.Backend = this.recline.Backend || {};
return dfd.promise();
}
});
- recline.Model.backends['dataproxy'] = new my.DataProxy();
-
}(jQuery, this.recline.Backend));
diff --git a/src/backend/elasticsearch.js b/src/backend/elasticsearch.js
index 6944a2f4..164393a8 100644
--- a/src/backend/elasticsearch.js
+++ b/src/backend/elasticsearch.js
@@ -20,6 +20,7 @@ this.recline.Backend = this.recline.Backend || {};
//
//
my.GDoc = my.Base.extend({
+ __type__: 'gdoc',
getUrl: function(dataset) {
var url = dataset.get('url');
if (url.indexOf('feeds/list') != -1) {
@@ -134,7 +135,6 @@ this.recline.Backend = this.recline.Backend || {};
return results;
}
});
- recline.Model.backends['gdocs'] = new my.GDoc();
}(jQuery, this.recline.Backend));
diff --git a/src/backend/memory.js b/src/backend/memory.js
index 49f03087..f79991e8 100644
--- a/src/backend/memory.js
+++ b/src/backend/memory.js
@@ -20,7 +20,7 @@ this.recline.Backend = this.recline.Backend || {};
if (!metadata.id) {
metadata.id = String(Math.floor(Math.random() * 100000000) + 1);
}
- var backend = recline.Model.backends['memory'];
+ var backend = new recline.Backend.Memory();
var datasetInfo = {
documents: data,
metadata: metadata
@@ -35,7 +35,7 @@ this.recline.Backend = this.recline.Backend || {};
}
}
backend.addDataset(datasetInfo);
- var dataset = new recline.Model.Dataset({id: metadata.id}, 'memory');
+ var dataset = new recline.Model.Dataset({id: metadata.id}, backend);
dataset.fetch();
return dataset;
};
@@ -70,6 +70,7 @@ this.recline.Backend = this.recline.Backend || {};
// etc ...
//
my.Memory = my.Base.extend({
+ __type__: 'memory',
initialize: function() {
this.datasets = {};
},
@@ -209,6 +210,5 @@ this.recline.Backend = this.recline.Backend || {};
return facetResults;
}
});
- recline.Model.backends['memory'] = new my.Memory();
}(jQuery, this.recline.Backend));
diff --git a/src/model.js b/src/model.js
index 5f834cad..137244d7 100644
--- a/src/model.js
+++ b/src/model.js
@@ -18,7 +18,7 @@ this.recline.Model = this.recline.Model || {};
//
// @property {number} docCount: total number of documents in this dataset
//
-// @property {Backend} backend: the Backend (instance) for this Dataset
+// @property {Backend} backend: the Backend (instance) for this Dataset.
//
// @property {Query} queryState: `Query` object which stores current
// queryState. queryState may be edited by other components (e.g. a query
@@ -28,14 +28,24 @@ this.recline.Model = this.recline.Model || {};
// Facets.
my.Dataset = Backbone.Model.extend({
__type__: 'Dataset',
+
// ### initialize
//
// Sets up instance properties (see above)
+ //
+ // @param {Object} model: standard set of model attributes passed to Backbone models
+ //
+ // @param {Object or String} backend: Backend instance (see
+ // `recline.Backend.Base`) or a string specifying that instance. The
+ // string specifying may be a full class path e.g.
+ // 'recline.Backend.ElasticSearch' or a simple name e.g.
+ // 'elasticsearch' or 'ElasticSearch' (in this case must be a Backend in
+ // recline.Backend module)
initialize: function(model, backend) {
_.bindAll(this, 'query');
this.backend = backend;
- if (backend && backend.constructor == String) {
- this.backend = my.backends[backend];
+ if (typeof(backend) === 'string') {
+ this.backend = this._backendFromString(backend);
}
this.fields = new my.FieldList();
this.currentDocuments = new my.DocumentList();
@@ -99,6 +109,35 @@ my.Dataset = Backbone.Model.extend({
data.docCount = this.docCount;
data.fields = this.fields.toJSON();
return data;
+ },
+
+ // ### _backendFromString(backendString)
+ //
+ // See backend argument to initialize for details
+ _backendFromString: function(backendString) {
+ var parts = backendString.split('.');
+ // walk through the specified path xxx.yyy.zzz to get the final object which should be backend class
+ var current = window;
+ for(ii=0;ii
-
+
diff --git a/test/model.test.js b/test/model.test.js
index 2625a7a4..2f0c4e6a 100644
--- a/test/model.test.js
+++ b/test/model.test.js
@@ -103,6 +103,16 @@ test('Dataset _prepareQuery', function () {
deepEqual(out, exp);
});
+test('Dataset _backendFromString', function () {
+ var dataset = new recline.Model.Dataset();
+
+ var out = dataset._backendFromString('recline.Backend.Memory');
+ equal(out.__type__, 'memory');
+
+ var out = dataset._backendFromString('dataproxy');
+ equal(out.__type__, 'dataproxy');
+});
+
// =================================
// Query
From 2a93aeb2c134485de72675ecab388f112867c873 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 22:47:16 +0100
Subject: [PATCH 37/48] [#88,state][s]: (and finally) introduce a
recline.View.DataExplorer.restore function that restores from a serialized
state.
* remove getState in favour of just using direct access to state object.
---
src/view.js | 38 +++++++++++++++++++++++++++++---------
test/view.test.js | 20 ++++++++++++++++----
2 files changed, 45 insertions(+), 13 deletions(-)
diff --git a/src/view.js b/src/view.js
index 0b46df21..6dedc111 100644
--- a/src/view.js
+++ b/src/view.js
@@ -318,10 +318,12 @@ my.DataExplorer = Backbone.View.extend({
var graphState = qs['view-graph'] || qs.graph;
graphState = graphState ? JSON.parse(graphState) : {};
var stateData = _.extend({
- readOnly: false,
query: query,
'view-graph': graphState,
- currentView: null
+ backend: this.model.backend.__type__,
+ dataset: this.model.toJSON(),
+ currentView: null,
+ readOnly: false
},
initialState);
this.state.set(stateData);
@@ -353,16 +355,34 @@ my.DataExplorer = Backbone.View.extend({
});
}
});
- },
-
- // ### getState
- //
- // Get the current state of dataset and views (see discussion of state above)
- getState: function() {
- return this.state;
}
});
+// ## restore
+//
+// Restore a DataExplorer instance from a serialized state including the associated dataset
+my.DataExplorer.restore = function(state) {
+ // hack-y - restoring a memory dataset does not mean much ...
+ var dataset = null;
+ if (state.backend === 'memory') {
+ dataset = recline.Backend.createDataset(
+ [{stub: 'this is a stub dataset because we do not restore memory datasets'}],
+ [],
+ state.dataset
+ );
+ } else {
+ dataset = new recline.Model.Dataset(
+ state.dataset,
+ state.backend
+ );
+ }
+ var explorer = new my.DataExplorer({
+ model: dataset,
+ state: state
+ });
+ return explorer;
+}
+
my.QueryEditor = Backbone.View.extend({
className: 'recline-query-editor',
template: ' \
diff --git a/test/view.test.js b/test/view.test.js
index 6a898989..456da7be 100644
--- a/test/view.test.js
+++ b/test/view.test.js
@@ -15,7 +15,7 @@ test('basic explorer functionality', function () {
$el.remove();
});
-test('getState', function () {
+test('get State', function () {
var $el = $('');
$('.fixtures .data-explorer-here').append($el);
var dataset = Fixture.getDataset();
@@ -23,11 +23,13 @@ test('getState', function () {
model: dataset,
el: $el
});
- var state = explorer.getState();
+ var state = explorer.state;
ok(state.get('query'));
equal(state.get('readOnly'), false);
equal(state.get('query').size, 100);
deepEqual(state.get('view-grid').hiddenFields, []);
+ equal(state.get('backend'), 'memory');
+ ok(state.get('dataset').id !== null);
$el.remove();
});
@@ -42,8 +44,18 @@ test('initialize state', function () {
}
}
});
- var state = explorer.getState();
- ok(state.get('readOnly'));
+ ok(explorer.state.get('readOnly'));
+});
+
+test('restore (from serialized state)', function() {
+ var dataset = Fixture.getDataset();
+ var explorer = new recline.View.DataExplorer({
+ model: dataset,
+ });
+ var state = explorer.state.toJSON();
+ var explorerNew = recline.View.DataExplorer.restore(state);
+ var out = explorerNew.state.toJSON();
+ equal(out.backend, state.backend);
});
})(this.jQuery);
From 3092ef6a8bd9c6578040a2bcf3382c51952268ca Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 23:03:31 +0100
Subject: [PATCH 38/48] [test][xs]: micro tidy-up (calling remove on view at
end of test in Grid View test).
---
test/view-grid.test.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/test/view-grid.test.js b/test/view-grid.test.js
index b415acde..4d2d0a96 100644
--- a/test/view-grid.test.js
+++ b/test/view-grid.test.js
@@ -53,6 +53,7 @@ test('new GridRow View', function () {
var tds = $el.find('td');
equal(tds.length, 3);
equal($(tds[1]).attr('data-field'), 'a');
+ view.remove();
});
})(this.jQuery);
From bcffe673369276be36dd051df6a04ef791d59471 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 23:08:42 +0100
Subject: [PATCH 39/48] [#88,refactor][s]: create recline.Model.Dataset.restore
function and move dataset restore stuff there from
recline.View.DataExplorer.restore.
---
src/model.js | 30 ++++++++++++++++++++++++++++++
src/view.js | 19 +++++--------------
2 files changed, 35 insertions(+), 14 deletions(-)
diff --git a/src/model.js b/src/model.js
index 137244d7..1464ec46 100644
--- a/src/model.js
+++ b/src/model.js
@@ -141,6 +141,36 @@ my.Dataset = Backbone.Model.extend({
}
});
+
+// ### Dataset.restore
+//
+// Restore a Dataset instance from a serialized state. Serialized state for a
+// Dataset is an Object like:
+//
+//
+// {
+// backend: {backend type - i.e. value of dataset.backend.__type__}
+// dataset: {result of dataset.toJSON()}
+// ...
+// }
+my.Dataset.restore = function(state) {
+ // hack-y - restoring a memory dataset does not mean much ...
+ var dataset = null;
+ if (state.backend === 'memory') {
+ dataset = recline.Backend.createDataset(
+ [{stub: 'this is a stub dataset because we do not restore memory datasets'}],
+ [],
+ state.dataset
+ );
+ } else {
+ dataset = new recline.Model.Dataset(
+ state.dataset,
+ state.backend
+ );
+ }
+ return dataset;
+};
+
// ## A Document (aka Row)
//
// A single entry or row in the dataset
diff --git a/src/view.js b/src/view.js
index 6dedc111..5e3a4c02 100644
--- a/src/view.js
+++ b/src/view.js
@@ -140,6 +140,10 @@ this.recline.View = this.recline.View || {};
// readOnly: (default: false) run in read-only mode
// }
//
+//
+// Note that at present we do *not* serialize information about the actual set
+// of views in use -- e.g. those specified by the views argument. Instead we
+// expect the client to have initialized the DataExplorer with the relevant views.
my.DataExplorer = Backbone.View.extend({
template: ' \
\
@@ -362,20 +366,7 @@ my.DataExplorer = Backbone.View.extend({
//
// Restore a DataExplorer instance from a serialized state including the associated dataset
my.DataExplorer.restore = function(state) {
- // hack-y - restoring a memory dataset does not mean much ...
- var dataset = null;
- if (state.backend === 'memory') {
- dataset = recline.Backend.createDataset(
- [{stub: 'this is a stub dataset because we do not restore memory datasets'}],
- [],
- state.dataset
- );
- } else {
- dataset = new recline.Model.Dataset(
- state.dataset,
- state.backend
- );
- }
+ var dataset = recline.Model.Dataset.restore(state);
var explorer = new my.DataExplorer({
model: dataset,
state: state
From 6a90189b468f15f6a5909d44b084e9558cd371ed Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 23:23:37 +0100
Subject: [PATCH 40/48] [test][xs]: remove console.log.
---
test/backend.test.js | 1 -
1 file changed, 1 deletion(-)
diff --git a/test/backend.test.js b/test/backend.test.js
index 62dea142..f7d96f60 100644
--- a/test/backend.test.js
+++ b/test/backend.test.js
@@ -103,7 +103,6 @@ test('Memory Backend: filters', function () {
});
test('Memory Backend: facet', function () {
- console.log('here');
var dataset = makeBackendDataset();
dataset.queryState.addFacet('country');
dataset.query().then(function() {
From 927bc3264775c8f201243d4935f45d5e3861d217 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Sun, 15 Apr 2012 23:26:57 +0100
Subject: [PATCH 41/48] [#88,view][s]: DataExplorer boots Grid, Graph and Map
view by default instead of just Grid.
* This makes DataExplorer.restore substantially more useful.
---
src/view.js | 24 +++++++++++++++++++-----
test/index.html | 6 ++++++
2 files changed, 25 insertions(+), 5 deletions(-)
diff --git a/src/view.js b/src/view.js
index 5e3a4c02..0d26d24f 100644
--- a/src/view.js
+++ b/src/view.js
@@ -105,7 +105,8 @@ this.recline.View = this.recline.View || {};
//
// **views**: (optional) the dataset views (Grid, Graph etc) for
// DataExplorer to show. This is an array of view hashes. If not provided
-// just initialize a Grid with id 'grid'. Example:
+// initialize with (recline.View.)Grid, Graph, and Map views (with obvious id
+// and labels!).
//
//
//
// Note that at present we do *not* serialize information about the actual set
-// of views in use -- e.g. those specified by the views argument. Instead we
-// expect the client to have initialized the DataExplorer with the relevant views.
+// of views in use -- e.g. those specified by the views argument -- but instead
+// expect either that the default views are fine or that the client to have
+// initialized the DataExplorer with the relevant views themselves.
my.DataExplorer = Backbone.View.extend({
template: ' \
\
@@ -189,8 +191,20 @@ my.DataExplorer = Backbone.View.extend({
id: 'grid',
label: 'Grid',
view: new my.Grid({
- model: this.model
- })
+ model: this.model
+ })
+ }, {
+ id: 'graph',
+ label: 'Graph',
+ view: new my.Graph({
+ model: this.model
+ })
+ }, {
+ id: 'map',
+ label: 'Map',
+ view: new my.Map({
+ model: this.model
+ })
}];
}
this.state = new recline.Model.ObjectState();
diff --git a/test/index.html b/test/index.html
index 6d0838a6..da0e90b8 100644
--- a/test/index.html
+++ b/test/index.html
@@ -4,12 +4,15 @@
Qunit Tests
+
+
+
@@ -29,10 +32,13 @@
+
+
+
From 0ead86d6d715e1425322680f43c7d1d3cf6f8cb9 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 00:13:14 +0100
Subject: [PATCH 42/48] [#88,view,state][s]: support for setting and getting
currentView.
* Also refactor so that dataset view switcher in DataExplorer runs via direct JS rather than routing (as have meant to do for a while). this is important because a) routing stuff is partly going away b) it's cleaner this way.
---
src/view.js | 41 ++++++++++++++++++++++++++++++-----------
test/view.test.js | 13 +++++++++++++
2 files changed, 43 insertions(+), 11 deletions(-)
diff --git a/src/view.js b/src/view.js
index 0d26d24f..27df520e 100644
--- a/src/view.js
+++ b/src/view.js
@@ -154,7 +154,7 @@ my.DataExplorer = Backbone.View.extend({
\
',
events: {
- 'click .menu-right a': 'onMenuClick'
+ 'click .menu-right a': '_onMenuClick',
+ 'click .navigation a': '_onSwitchView'
},
initialize: function(options) {
@@ -207,10 +208,10 @@ my.DataExplorer = Backbone.View.extend({
})
}];
}
- this.state = new recline.Model.ObjectState();
// these must be called after pageViews are created
- this._setupState(options.state);
this.render();
+ // should come after render as may need to interact with elements in the view
+ this._setupState(options.state);
this.router = new Backbone.Router();
this.setupRouting();
@@ -299,10 +300,10 @@ my.DataExplorer = Backbone.View.extend({
});
},
- updateNav: function(pageName, queryString) {
+ updateNav: function(pageName) {
this.el.find('.navigation li').removeClass('active');
this.el.find('.navigation li a').removeClass('disabled');
- var $el = this.el.find('.navigation li a[href=#' + pageName + ']');
+ var $el = this.el.find('.navigation li a[data-view="' + pageName + '"]');
$el.parent().addClass('active');
$el.addClass('disabled');
// show the specific page
@@ -317,7 +318,7 @@ my.DataExplorer = Backbone.View.extend({
});
},
- onMenuClick: function(e) {
+ _onMenuClick: function(e) {
e.preventDefault();
var action = $(e.target).attr('data-action');
if (action === 'filters') {
@@ -327,29 +328,47 @@ my.DataExplorer = Backbone.View.extend({
}
},
+ _onSwitchView: function(e) {
+ e.preventDefault();
+ var viewName = $(e.target).attr('data-view');
+ this.updateNav(viewName);
+ this.state.set({currentView: viewName});
+ },
+
+ // create a state object for this view and do the job of
+ //
+ // a) initializing it from both data passed in and other sources (e.g. hash url)
+ //
+ // b) ensure the state object is updated in responese to changes in subviews, query etc.
_setupState: function(initialState) {
var self = this;
+ // get data from the query string / hash url plus some defaults
var qs = my.parseHashQueryString();
var query = qs.reclineQuery;
query = query ? JSON.parse(query) : self.model.queryState.toJSON();
// backwards compatability (now named view-graph but was named graph)
var graphState = qs['view-graph'] || qs.graph;
graphState = graphState ? JSON.parse(graphState) : {};
+
+ // now get default data + hash url plus initial state and initial our state object with it
var stateData = _.extend({
query: query,
'view-graph': graphState,
backend: this.model.backend.__type__,
dataset: this.model.toJSON(),
- currentView: null,
+ currentView: this.pageViews[0].id,
readOnly: false
},
initialState);
- this.state.set(stateData);
+ this.state = new recline.Model.ObjectState(stateData);
// now do updates based on state
if (this.state.get('readOnly')) {
this.setReadOnly();
}
+ if (this.state.get('currentView')) {
+ this.updateNav(this.state.get('currentView'));
+ }
_.each(this.pageViews, function(pageView) {
var viewId = 'view-' + pageView.id;
if (viewId in self.state.attributes) {
@@ -357,7 +376,7 @@ my.DataExplorer = Backbone.View.extend({
}
});
- // bind for changes state in associated objects
+ // finally ensure we update our state object when state of sub-object changes so that state is always up to date
this.model.queryState.bind('change', function() {
self.state.set({queryState: self.model.queryState.toJSON()});
});
@@ -376,7 +395,7 @@ my.DataExplorer = Backbone.View.extend({
}
});
-// ## restore
+// ### DataExplorer.restore
//
// Restore a DataExplorer instance from a serialized state including the associated dataset
my.DataExplorer.restore = function(state) {
diff --git a/test/view.test.js b/test/view.test.js
index 456da7be..cb0d4a0c 100644
--- a/test/view.test.js
+++ b/test/view.test.js
@@ -26,6 +26,7 @@ test('get State', function () {
var state = explorer.state;
ok(state.get('query'));
equal(state.get('readOnly'), false);
+ equal(state.get('currentView'), 'grid');
equal(state.get('query').size, 100);
deepEqual(state.get('view-grid').hiddenFields, []);
equal(state.get('backend'), 'memory');
@@ -34,17 +35,29 @@ test('get State', function () {
});
test('initialize state', function () {
+ var $el = $('');
+ $('.fixtures .data-explorer-here').append($el);
var dataset = Fixture.getDataset();
var explorer = new recline.View.DataExplorer({
model: dataset,
+ el: $el,
state: {
readOnly: true,
+ currentView: 'graph',
'view-grid': {
hiddenFields: ['x']
}
}
});
ok(explorer.state.get('readOnly'));
+ ok(explorer.state.get('currentView'), 'graph');
+ // check the correct view is visible
+ var css = explorer.el.find('.navigation a[data-view="graph"]').attr('class').split(' ');
+ ok(_.contains(css, 'disabled'), css);
+
+ var css = explorer.el.find('.navigation a[data-view="grid"]').attr('class').split(' ');
+ ok(!(_.contains(css, 'disabled')), css);
+ $el.remove();
});
test('restore (from serialized state)', function() {
From 2d636b0eb8bbcde418e52f97c5525a2c415df4cc Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 03:02:42 +0100
Subject: [PATCH 43/48] [css/grid.css][xs]: vertical-align top for grid cells.
---
css/grid.css | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/css/grid.css b/css/grid.css
index 4e4bd806..aeb9984e 100644
--- a/css/grid.css
+++ b/css/grid.css
@@ -23,6 +23,10 @@
text-align: left;
}
+.recline-grid td {
+ vertical-align: top;
+}
+
.recline-grid tr td:first-child, .recline-grid tr th:first-child {
width: 20px;
}
From 40a771c38bec81c6ed7060da83042b7fb462581f Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 03:06:31 +0100
Subject: [PATCH 44/48] [app][s]: refactor app to be a backbone view.
---
app/index.html | 2 +
app/js/app.js | 177 +++++++++++++++++++++++--------------------------
2 files changed, 84 insertions(+), 95 deletions(-)
diff --git a/app/index.html b/app/index.html
index db5b8917..29ff9781 100644
--- a/app/index.html
+++ b/app/index.html
@@ -60,6 +60,7 @@
+
@@ -152,6 +153,7 @@
+
diff --git a/app/js/app.js b/app/js/app.js
index 807b3c63..956e6f53 100755
--- a/app/js/app.js
+++ b/app/js/app.js
@@ -1,7 +1,8 @@
-$(function() {
+jQuery(function($) {
var qs = recline.View.parseQueryString(window.location.search);
+ var dataest = null;
if (qs.url) {
- var dataset = new recline.Model.Dataset({
+ dataset = new recline.Model.Dataset({
id: 'my-dataset',
url: qs.url,
webstore_url: qs.url
@@ -12,67 +13,90 @@ $(function() {
dataset = localDataset();
}
- createExplorer(dataset);
+ var app = new ExplorerApp({
+ model: dataset,
+ el: $('.recline-app')
+ })
Backbone.history.start();
-
- // setup the loader menu in top bar
- setupLoader(createExplorer);
});
-// make Explorer creation / initialization in a function so we can call it
-// again and again
-function createExplorer(dataset) {
- // remove existing data explorer view
- var reload = false;
- if (window.dataExplorer) {
- window.dataExplorer.remove();
- reload = true;
- }
- window.dataExplorer = null;
- var $el = $('');
- $el.appendTo($('.data-explorer-here'));
- var views = standardViews(dataset);
- window.dataExplorer = new recline.View.DataExplorer({
- el: $el
- , model: dataset
- , views: views
- });
- // HACK (a bit). Issue is that Backbone will not trigger the route
- // if you are already at that location so we have to make sure we genuinely switch
- if (reload) {
- window.dataExplorer.router.navigate('graph');
- window.dataExplorer.router.navigate('', true);
- }
-}
+var ExplorerApp = Backbone.View.extend({
+ events: {
+ 'submit form.js-import-url': '_onImportURL',
+ 'submit .js-import-dialog-file form': '_onImportFile'
+ },
-// convenience function
-function standardViews(dataset) {
- var views = [
- {
- id: 'grid',
- label: 'Grid',
- view: new recline.View.Grid({
- model: dataset
- })
- },
- {
- id: 'graph',
- label: 'Graph',
- view: new recline.View.Graph({
- model: dataset
- })
- },
- {
- id: 'map',
- label: 'Map',
- view: new recline.View.Map({
- model: dataset
- })
+ initialize: function() {
+ this.explorer = null;
+ this.explorerDiv = $('.data-explorer-here');
+ this.createExplorer(this.model);
+ },
+
+ // make Explorer creation / initialization in a function so we can call it
+ // again and again
+ createExplorer: function(dataset) {
+ // remove existing data explorer view
+ var reload = false;
+ if (this.dataExplorer) {
+ this.dataExplorer.remove();
+ reload = true;
}
+ this.dataExplorer = null;
+ var $el = $('');
+ $el.appendTo(this.explorerDiv);
+ this.dataExplorer = new recline.View.DataExplorer({
+ el: $el
+ , model: dataset
+ });
+ // HACK (a bit). Issue is that Backbone will not trigger the route
+ // if you are already at that location so we have to make sure we genuinely switch
+ if (reload) {
+ this.dataExplorer.router.navigate('graph');
+ this.dataExplorer.router.navigate('', true);
+ }
+ },
- ];
- return views;
-}
+ // setup the loader menu in top bar
+ setupLoader: function(callback) {
+ // pre-populate webstore load form with an example url
+ var demoUrl = 'http://thedatahub.org/api/data/b9aae52b-b082-4159-b46f-7bb9c158d013';
+ $('form.js-import-url input[name="source"]').val(demoUrl);
+ },
+
+ _onImportURL: function(e) {
+ e.preventDefault();
+ $('.modal.js-import-dialog-url').modal('hide');
+ var $form = $(e.target);
+ var source = $form.find('input[name="source"]').val();
+ var type = $form.find('select[name="backend_type"]').val();
+ var dataset = new recline.Model.Dataset({
+ id: 'my-dataset',
+ url: source,
+ webstore_url: source
+ },
+ type
+ );
+ this.createExplorer(dataset);
+ },
+
+ _onImportFile: function(e) {
+ var self = this;
+ e.preventDefault();
+ var $form = $(e.target);
+ $('.modal.js-import-dialog-file').modal('hide');
+ var $file = $form.find('input[type="file"]')[0];
+ var file = $file.files[0];
+ var options = {
+ separator : $form.find('input[name="separator"]').val(),
+ encoding : $form.find('input[name="encoding"]').val()
+ };
+ recline.Backend.loadFromCSVFile(file, function(dataset) {
+ self.createExplorer(dataset)
+ },
+ options
+ );
+ }
+});
// provide a demonstration in memory dataset
function localDataset() {
@@ -83,7 +107,7 @@ function localDataset() {
, name: '1-my-test-dataset'
, id: datasetId
},
-fields: [{id: 'x'}, {id: 'y'}, {id: 'z'}, {id: 'country'}, {id: 'label'},{id: 'lat'},{id: 'lon'}],
+ fields: [{id: 'x'}, {id: 'y'}, {id: 'z'}, {id: 'country'}, {id: 'label'},{id: 'lat'},{id: 'lon'}],
documents: [
{id: 0, x: 1, y: 2, z: 3, country: 'DE', label: 'first', lat:52.56, lon:13.40}
, {id: 1, x: 2, y: 4, z: 6, country: 'UK', label: 'second', lat:54.97, lon:-1.60}
@@ -100,40 +124,3 @@ fields: [{id: 'x'}, {id: 'y'}, {id: 'z'}, {id: 'country'}, {id: 'label'},{id: 'l
return dataset;
}
-// setup the loader menu in top bar
-function setupLoader(callback) {
- // pre-populate webstore load form with an example url
- var demoUrl = 'http://thedatahub.org/api/data/b9aae52b-b082-4159-b46f-7bb9c158d013';
- $('form.js-import-url input[name="source"]').val(demoUrl);
- $('form.js-import-url').submit(function(e) {
- e.preventDefault();
- $('.modal.js-import-dialog-url').modal('hide');
- var $form = $(e.target);
- var source = $form.find('input[name="source"]').val();
- var type = $form.find('select[name="backend_type"]').val();
- var dataset = new recline.Model.Dataset({
- id: 'my-dataset',
- url: source,
- webstore_url: source
- },
- type
- );
- callback(dataset);
- });
-
- $('.js-import-dialog-file form').submit(function(e) {
- e.preventDefault();
- var $form = $(e.target);
- $('.modal.js-import-dialog-file').modal('hide');
- var $file = $form.find('input[type="file"]')[0];
- var file = $file.files[0];
- var options = {
- separator : $form.find('input[name="separator"]').val(),
- encoding : $form.find('input[name="encoding"]').val()
- };
- recline.Backend.loadFromCSVFile(file, function(dataset) {
- callback(dataset)
- }, options);
- });
-}
-
From 53e099beda3d41ea21dc906f3cd5a3beff0dc582 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 15:15:59 +0100
Subject: [PATCH 45/48] [test][xs]: make fixtures dataset same as for demo.
---
test/base.js | 22 +++++++++++++++-------
1 file changed, 15 insertions(+), 7 deletions(-)
diff --git a/test/base.js b/test/base.js
index bffbba1c..729e1178 100644
--- a/test/base.js
+++ b/test/base.js
@@ -1,13 +1,21 @@
var Fixture = {
getDataset: function() {
- var fields = [{id: 'x'}, {id: 'y'}, {id: 'z'}, {id: 'country'}, {id: 'label'},{id: 'lat'},{id: 'lon'}];
+ var fields = [
+ {id: 'x'},
+ {id: 'y'},
+ {id: 'z'},
+ {id: 'country'},
+ {id: 'label'},
+ {id: 'lat'},
+ {id: 'lon'}
+ ];
var documents = [
- {id: 0, x: 1, y: 2, z: 3, country: 'DE', lat:52.56, lon:13.40}
- , {id: 1, x: 2, y: 4, z: 6, country: 'UK', lat:54.97, lon:-1.60}
- , {id: 2, x: 3, y: 6, z: 9, country: 'US', lat:40.00, lon:-75.5}
- , {id: 3, x: 4, y: 8, z: 12, country: 'UK', lat:57.27, lon:-6.20}
- , {id: 4, x: 5, y: 10, z: 15, country: 'UK', lat:51.58, lon:0}
- , {id: 5, x: 6, y: 12, z: 18, country: 'DE', lat:51.04, lon:7.9}
+ {id: 0, x: 1, y: 2, z: 3, country: 'DE', label: 'first', lat:52.56, lon:13.40},
+ {id: 1, x: 2, y: 4, z: 6, country: 'UK', label: 'second', lat:54.97, lon:-1.60},
+ {id: 2, x: 3, y: 6, z: 9, country: 'US', label: 'third', lat:40.00, lon:-75.5},
+ {id: 3, x: 4, y: 8, z: 12, country: 'UK', label: 'fourth', lat:57.27, lon:-6.20},
+ {id: 4, x: 5, y: 10, z: 15, country: 'UK', label: 'fifth', lat:51.58, lon:0},
+ {id: 5, x: 6, y: 12, z: 18, country: 'DE', label: 'sixth', lat:51.04, lon:7.9}
];
var dataset = recline.Backend.createDataset(documents, fields);
return dataset;
From a42840cdf3231a050a784d7104d5786818fdfa76 Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 15:16:28 +0100
Subject: [PATCH 46/48] [#88,model/state][xs]: can just specify a url instead
of full dataset object when restoring from state (easier and good for
backwards compatability).
---
src/model.js | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/src/model.js b/src/model.js
index 1464ec46..4145507b 100644
--- a/src/model.js
+++ b/src/model.js
@@ -150,17 +150,22 @@ my.Dataset = Backbone.Model.extend({
//
// {
// backend: {backend type - i.e. value of dataset.backend.__type__}
-// dataset: {result of dataset.toJSON()}
+// dataset: {dataset info needed for loading -- result of dataset.toJSON() would be sufficient but can be simpler }
+// // convenience - if url provided and dataste not this be used as dataset url
+// url: {dataset url}
// ...
// }
my.Dataset.restore = function(state) {
// hack-y - restoring a memory dataset does not mean much ...
var dataset = null;
+ if (state.url && !state.dataset) {
+ state.dataset = {url: state.url};
+ }
if (state.backend === 'memory') {
dataset = recline.Backend.createDataset(
[{stub: 'this is a stub dataset because we do not restore memory datasets'}],
[],
- state.dataset
+ state.dataset // metadata
);
} else {
dataset = new recline.Model.Dataset(
From 0f0fa633a1d8f31e1bf1662d7b6d310f6c32805f Mon Sep 17 00:00:00 2001
From: Rufus Pollock
Date: Mon, 16 Apr 2012 15:17:19 +0100
Subject: [PATCH 47/48] [#67,app][s]: first pass at sharable link support in
app (though seems rather buggy).
---
app/index.html | 17 +++++++++++++++
app/js/app.js | 56 +++++++++++++++++++++++++++++++++-----------------
src/view.js | 3 +++
3 files changed, 57 insertions(+), 19 deletions(-)
diff --git a/app/index.html b/app/index.html
index 29ff9781..cfd9492e 100644
--- a/app/index.html
+++ b/app/index.html
@@ -81,6 +81,12 @@
+