Last active
August 29, 2015 14:18
-
-
Save hogart/caa28547667cc522f129 to your computer and use it in GitHub Desktop.
Backbone.Model with auto-properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var Backbone = require('backbone'); | |
var ModelAbstract = Backbone.Model.extend({ | |
/** | |
* Create calculatable properties. | |
* @example | |
* __autos__: { | |
* 'fieldName': ['torrent dont_seed', function () {}] | |
* 'fieldName': ['torrent dont_seed', 'methodName'], // will be used this.methodName | |
* 'fieldName': ['torrent dont_seed'], // will be used this.fieldName | |
* } | |
* function should return value which will be set to `fieldName` model field. | |
* | |
* @param {Object} [autos=this.__autos__] | |
* @protected | |
*/ | |
_processAutos: function (autos) { | |
if (!autos) { | |
autos = _.result(this, '__autos__') | |
} | |
if (!autos) { | |
return; | |
} | |
Object.keys(autos).forEach(function (autoName) { | |
var handler = autos[autoName]; | |
var keys = handler[0]; | |
var callback; | |
if (handler.length === 2) { | |
callback = typeof handler[1] === 'string' ? this[handler[1]] : handler[1]; | |
} else { | |
callback = this[autoName]; | |
} | |
this._genAutoProp(keys, autoName, callback); | |
}, this); | |
}, | |
/** | |
* | |
* @param {String} keys space-delimited field names | |
* @param {String} autoName | |
* @param {Function} callback | |
* @protected | |
*/ | |
_genAutoProp: function (keys, autoName, callback) { | |
var eventName = 'change:' + keys.replace(/ /g, ' change:'); | |
var handler = function () { | |
this.set(autoName, callback.call(this)) | |
}.bind(this); | |
this.on(eventName, function () { | |
setTimeout(handler, 0) | |
}); | |
handler(); // fire right at the start | |
}, | |
initialize: function (attributes, options) { | |
this._processAutos(); | |
ModelAbstract.__super__.initialize.apply(this, arguments); | |
} | |
}); | |
module.exports = ModelAbstract; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment