Reputation: 2417
I'm new to JS development, and I find myself spending more than desirable attention fixing bugs caused by typos in model attributes, especially usages of model.get(). While my unit test do catch most of these, it's still annoying to fix and having to remember the names when coding. Is there something that can warn me about these typos?
Upvotes: 2
Views: 93
Reputation: 6552
First, install the plugin _super:
https://github.com/lukasolson/Backbone-Super
Now create an abstract Model:
YourAbstractModel = Backbone.Model.extend({
get : function(attr){
if( !_.has(this.defaults, attr) ){
throw 'Invalid attribute: ' + attr;
}
return this._super(attr);
}
});
Your models should extend the abstract instead of the Backbone.Model(and you should set defaults).
Upvotes: 1
Reputation: 1958
One strategy that we use is to define a hash and use them for the setters and getters
var ATTRS = {
attr1: 'attr1',
attr2: 'attr2'
}
model.set (ATTRS.attr1, 'attr1_val');
model.get (ATTRS.attr1);
For some cases like since JS wont allow to use variable on the left-hand-side of a hash, you wont be able to use this. But for the most part, it helps eliminate most simple typo errors
{ ATTRS.attr: 'def_val' } // this will give an error
Hope this help
Upvotes: 3
Reputation: 12736
I think that testing is the best approach.
Including validation/spellcheck code, that will become a part of your production application eventually, is a bad idea. If you type the name of the variable incorrectly - it should be discovered by your development-time testing, not some run-time validation.
Upvotes: 0