简体   繁体   中英

Backbone.js: How to catch typos when working with model attributes?

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?

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM