Metamaps.Backbone standard style

This commit is contained in:
Devin Howard 2016-03-27 19:46:36 +08:00
parent 5a3ab025b7
commit e8c55df4e8

View file

@ -1,187 +1,194 @@
Metamaps.Backbone = {}; /* global Metamaps, Backbone, _, $ */
/*
* Metamaps.Backbone.js.erb
*
* Dependencies:
* - Metamaps.Active
* - Metamaps.Loading
* - Metamaps.Map
* - Metamaps.Mapper
* - Metamaps.Realtime
*/
Metamaps.Backbone = {}
Metamaps.Backbone.Map = Backbone.Model.extend({ Metamaps.Backbone.Map = Backbone.Model.extend({
urlRoot: '/maps', urlRoot: '/maps',
blacklist: ['created_at', 'updated_at', 'created_at_clean', 'updated_at_clean', 'user_name', 'contributor_count', 'topic_count', 'synapse_count', 'topics', 'synapses', 'mappings', 'mappers'], blacklist: ['created_at', 'updated_at', 'created_at_clean', 'updated_at_clean', 'user_name', 'contributor_count', 'topic_count', 'synapse_count', 'topics', 'synapses', 'mappings', 'mappers'],
toJSON: function (options) { toJSON: function (options) {
return _.omit(this.attributes, this.blacklist); return _.omit(this.attributes, this.blacklist)
}, },
save: function (key, val, options) { save: function (key, val, options) {
var attrs
var attrs;
// Handle both `"key", value` and `{key: value}` -style arguments. // Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') { if (key == null || typeof key === 'object') {
attrs = key; attrs = key
options = val; options = val
} else { } else {
(attrs = {})[key] = val; (attrs = {})[key] = val
} }
var newOptions = options || {}; var newOptions = options || {}
var s = newOptions.success; var s = newOptions.success
newOptions.success = function (model, response, opt) { newOptions.success = function (model, response, opt) {
if (s) s(model, response, opt); if (s) s(model, response, opt)
model.trigger('saved'); model.trigger('saved')
}; }
return Backbone.Model.prototype.save.call(this, attrs, newOptions); return Backbone.Model.prototype.save.call(this, attrs, newOptions)
}, },
initialize: function () { initialize: function () {
this.on('changeByOther', this.updateView); this.on('changeByOther', this.updateView)
this.on('saved', this.savedEvent); this.on('saved', this.savedEvent)
}, },
savedEvent: function() { savedEvent: function () {
Metamaps.Realtime.sendMapChange(this); Metamaps.Realtime.sendMapChange(this)
}, },
authorizeToEdit: function (mapper) { authorizeToEdit: function (mapper) {
if (mapper && (this.get('permission') === "commons" || this.get('user_id') === mapper.get('id'))) return true; if (mapper && (this.get('permission') === 'commons' || this.get('user_id') === mapper.get('id'))) return true
else return false; else return false
}, },
authorizePermissionChange: function (mapper) { authorizePermissionChange: function (mapper) {
if (mapper && this.get('user_id') === mapper.get('id')) return true; if (mapper && this.get('user_id') === mapper.get('id')) return true
else return false; else return false
}, },
getUser: function () { getUser: function () {
return Metamaps.Mapper.get(this.get('user_id')); return Metamaps.Mapper.get(this.get('user_id'))
}, },
fetchContained: function () { fetchContained: function () {
var bb = Metamaps.Backbone; var bb = Metamaps.Backbone
var that = this; var that = this
var start = function (data) { var start = function (data) {
that.set('mappers', new bb.MapperCollection(data.mappers)); that.set('mappers', new bb.MapperCollection(data.mappers))
that.set('topics', new bb.TopicCollection(data.topics)); that.set('topics', new bb.TopicCollection(data.topics))
that.set('synapses', new bb.SynapseCollection(data.synapses)); that.set('synapses', new bb.SynapseCollection(data.synapses))
that.set('mappings', new bb.MappingCollection(data.mappings)); that.set('mappings', new bb.MappingCollection(data.mappings))
}; }
var e = $.ajax({ $.ajax({
url: "/maps/" + this.id + "/contains.json", url: '/maps/' + this.id + '/contains.json',
success: start, success: start,
error: errorFunc,
async: false async: false
}); })
}, },
getTopics: function () { getTopics: function () {
if (!this.get('topics')) { if (!this.get('topics')) {
this.fetchContained(); this.fetchContained()
} }
return this.get('topics'); return this.get('topics')
}, },
getSynapses: function () { getSynapses: function () {
if (!this.get('synapses')) { if (!this.get('synapses')) {
this.fetchContained(); this.fetchContained()
} }
return this.get('synapses'); return this.get('synapses')
}, },
getMappings: function () { getMappings: function () {
if (!this.get('mappings')) { if (!this.get('mappings')) {
this.fetchContained(); this.fetchContained()
} }
return this.get('mappings'); return this.get('mappings')
}, },
getMappers: function () { getMappers: function () {
if (!this.get('mappers')) { if (!this.get('mappers')) {
this.fetchContained(); this.fetchContained()
} }
return this.get('mappers'); return this.get('mappers')
}, },
attrForCards: function () { attrForCards: function () {
function capitalize(string) { function capitalize (string) {
return string.charAt(0).toUpperCase() + string.slice(1); return string.charAt(0).toUpperCase() + string.slice(1)
} }
var n = this.get('name'); var n = this.get('name')
var d = this.get('desc'); var d = this.get('desc')
var maxNameLength = 32; var maxNameLength = 32
var maxDescLength = 118; var maxDescLength = 118
var truncatedName = n ? (n.length > maxNameLength ? n.substring(0, maxNameLength) + "..." : n) : ""; var truncatedName = n ? (n.length > maxNameLength ? n.substring(0, maxNameLength) + '...' : n) : ''
var truncatedDesc = d ? (d.length > maxDescLength ? d.substring(0, maxDescLength) + "..." : d) : ""; var truncatedDesc = d ? (d.length > maxDescLength ? d.substring(0, maxDescLength) + '...' : d) : ''
var obj = { var obj = {
id: this.id, id: this.id,
name: truncatedName, name: truncatedName,
fullName: n, fullName: n,
desc: truncatedDesc, desc: truncatedDesc,
permission: this.get("permission") ? capitalize(this.get("permission")) : "Commons", permission: this.get('permission') ? capitalize(this.get('permission')) : 'Commons',
editPermission: this.authorizeToEdit(Metamaps.Active.Mapper) ? 'canEdit' : 'cannotEdit', editPermission: this.authorizeToEdit(Metamaps.Active.Mapper) ? 'canEdit' : 'cannotEdit',
contributor_count_number: '<span class="cCountColor">' + this.get('contributor_count') + '</span>', contributor_count_number: '<span class="cCountColor">' + this.get('contributor_count') + '</span>',
contributor_count_string: this.get('contributor_count') == 1 ? ' contributor' : ' contributors', contributor_count_string: this.get('contributor_count') === 1 ? ' contributor' : ' contributors',
topic_count_number: '<span class="tCountColor">' + this.get('topic_count') + '</span>', topic_count_number: '<span class="tCountColor">' + this.get('topic_count') + '</span>',
topic_count_string: this.get('topic_count') == 1 ? ' topic' : ' topics', topic_count_string: this.get('topic_count') === 1 ? ' topic' : ' topics',
synapse_count_number: '<span class="sCountColor">' + this.get('synapse_count') + '</span>', synapse_count_number: '<span class="sCountColor">' + this.get('synapse_count') + '</span>',
synapse_count_string: this.get('synapse_count') == 1 ? ' synapse' : ' synapses', synapse_count_string: this.get('synapse_count') === 1 ? ' synapse' : ' synapses',
screenshot: '<img src="' + this.get('screenshot_url') + '" />' screenshot: '<img src="' + this.get('screenshot_url') + '" />'
}; }
return obj; return obj
}, },
updateView: function() { updateView: function () {
var map = Metamaps.Active.Map; var map = Metamaps.Active.Map
var isActiveMap = this.id === map.id; var isActiveMap = this.id === map.id
var authorized = map && map.authorizeToEdit(Metamaps.Active.Mapper) ? 'canEditMap' : '';
var commonsMap = map && map.get('permission') === 'commons' ? 'commonsMap' : '';
if (isActiveMap) { if (isActiveMap) {
Metamaps.Map.InfoBox.updateNameDescPerm(this.get('name'), this.get('desc'), this.get('permission')); Metamaps.Map.InfoBox.updateNameDescPerm(this.get('name'), this.get('desc'), this.get('permission'))
this.updateMapWrapper(); this.updateMapWrapper()
} }
}, },
updateMapWrapper: function() { updateMapWrapper: function () {
var map = Metamaps.Active.Map; var map = Metamaps.Active.Map
var isActiveMap = this.id === map.id; var isActiveMap = this.id === map.id
var authorized = map && map.authorizeToEdit(Metamaps.Active.Mapper) ? 'canEditMap' : ''; var authorized = map && map.authorizeToEdit(Metamaps.Active.Mapper) ? 'canEditMap' : ''
var commonsMap = map && map.get('permission') === 'commons' ? 'commonsMap' : ''; var commonsMap = map && map.get('permission') === 'commons' ? 'commonsMap' : ''
if (isActiveMap) { if (isActiveMap) {
$('.wrapper').removeClass('canEditMap commonsMap').addClass(authorized + ' ' + commonsMap); $('.wrapper').removeClass('canEditMap commonsMap').addClass(authorized + ' ' + commonsMap)
} }
} }
}); })
Metamaps.Backbone.MapsCollection = Backbone.Collection.extend({ Metamaps.Backbone.MapsCollection = Backbone.Collection.extend({
model: Metamaps.Backbone.Map, model: Metamaps.Backbone.Map,
initialize: function(models, options) { initialize: function (models, options) {
this.id = options.id; this.id = options.id
this.sortBy = options.sortBy; this.sortBy = options.sortBy
if (options.mapperId) { if (options.mapperId) {
this.mapperId = options.mapperId; this.mapperId = options.mapperId
} }
// this.page represents the NEXT page to fetch // this.page represents the NEXT page to fetch
this.page = models.length > 0 ? (models.length < 20 ? "loadedAll" : 2) : 1; this.page = models.length > 0 ? (models.length < 20 ? 'loadedAll' : 2) : 1
}, },
url: function() { url: function () {
if (!this.mapperId) { if (!this.mapperId) {
return '/explore/' + this.id + '.json'; return '/explore/' + this.id + '.json'
} } else {
else { return '/explore/mapper/' + this.mapperId + '.json'
return '/explore/mapper/' + this.mapperId + '.json';
} }
}, },
comparator: function (a, b) { comparator: function (a, b) {
a = a.get(this.sortBy); a = a.get(this.sortBy)
b = b.get(this.sortBy); b = b.get(this.sortBy)
var temp; var temp
if (this.sortBy === 'name') { if (this.sortBy === 'name') {
a = a ? a.toLowerCase() : ""; a = a ? a.toLowerCase() : ''
b = b ? b.toLowerCase() : ""; b = b ? b.toLowerCase() : ''
} } else {
else {
// this is for updated_at and created_at // this is for updated_at and created_at
temp = a; temp = a
a = b; a = b
b = temp; b = temp
a = (new Date(a)).getTime(); a = (new Date(a)).getTime()
b = (new Date(b)).getTime(); b = (new Date(b)).getTime()
} }
return a > b ? 1 : a < b ? -1 : 0; return a > b ? 1 : a < b ? -1 : 0
}, },
getMaps: function (cb) { getMaps: function (cb) {
var self = this
var self = this; Metamaps.Loading.show()
Metamaps.Loading.show(); if (this.page !== 'loadedAll') {
var numBefore = this.length
if (this.page != "loadedAll") {
var numBefore = this.length;
this.fetch({ this.fetch({
remove: false, remove: false,
silent: true, silent: true,
@ -189,59 +196,61 @@ Metamaps.Backbone.MapsCollection = Backbone.Collection.extend({
success: function (collection, response, options) { success: function (collection, response, options) {
// you can pass additional options to the event you trigger here as well // you can pass additional options to the event you trigger here as well
if (collection.length - numBefore < 20) { if (collection.length - numBefore < 20) {
self.page = "loadedAll"; self.page = 'loadedAll'
} else {
self.page += 1
} }
else self.page += 1; self.trigger('successOnFetch', cb)
self.trigger('successOnFetch', cb);
}, },
error: function (collection, response, options) { error: function (collection, response, options) {
// you can pass additional options to the event you trigger here as well // you can pass additional options to the event you trigger here as well
self.trigger('errorOnFetch'); self.trigger('errorOnFetch')
} }
}); })
} } else {
else { self.trigger('successOnFetch', cb)
self.trigger('successOnFetch', cb);
} }
} }
}); })
Metamaps.Backbone.Message = Backbone.Model.extend({ Metamaps.Backbone.Message = Backbone.Model.extend({
urlRoot: '/messages', urlRoot: '/messages',
blacklist: ['created_at', 'updated_at'], blacklist: ['created_at', 'updated_at'],
toJSON: function (options) { toJSON: function (options) {
return _.omit(this.attributes, this.blacklist); return _.omit(this.attributes, this.blacklist)
}, },
prepareLiForFilter: function () { prepareLiForFilter: function () {
/*var li = ''; /* var li = ''
li += '<li data-id="' + this.id.toString() + '">'; * li += '<li data-id="' + this.id.toString() + '">'
li += '<img src="' + this.get("image") + '" data-id="' + this.id.toString() + '"'; * li += '<img src="' + this.get("image") + '" data-id="' + this.id.toString() + '"'
li += ' alt="' + this.get('name') + '" />'; * li += ' alt="' + this.get('name') + '" />'
li += '<p>' + this.get('name') + '</p></li>'; * li += '<p>' + this.get('name') + '</p></li>'
return li;*/ * return li
*/
} }
}); })
Metamaps.Backbone.MessageCollection = Backbone.Collection.extend({ Metamaps.Backbone.MessageCollection = Backbone.Collection.extend({
model: Metamaps.Backbone.Message, model: Metamaps.Backbone.Message,
url: '/messages' url: '/messages'
}); })
Metamaps.Backbone.Mapper = Backbone.Model.extend({ Metamaps.Backbone.Mapper = Backbone.Model.extend({
urlRoot: '/users', urlRoot: '/users',
blacklist: ['created_at', 'updated_at'], blacklist: ['created_at', 'updated_at'],
toJSON: function (options) { toJSON: function (options) {
return _.omit(this.attributes, this.blacklist); return _.omit(this.attributes, this.blacklist)
}, },
prepareLiForFilter: function () { prepareLiForFilter: function () {
var li = ''; var li = ''
li += '<li data-id="' + this.id.toString() + '">'; li += '<li data-id="' + this.id.toString() + '">'
li += '<img src="' + this.get("image") + '" data-id="' + this.id.toString() + '"'; li += '<img src="' + this.get('image') + '" data-id="' + this.id.toString() + '"'
li += ' alt="' + this.get('name') + '" />'; li += ' alt="' + this.get('name') + '" />'
li += '<p>' + this.get('name') + '</p></li>'; li += '<p>' + this.get('name') + '</p></li>'
return li; return li
} }
}); })
Metamaps.Backbone.MapperCollection = Backbone.Collection.extend({ Metamaps.Backbone.MapperCollection = Backbone.Collection.extend({
model: Metamaps.Backbone.Mapper, model: Metamaps.Backbone.Mapper,
url: '/users' url: '/users'
}); })