简体   繁体   English

Backbone.js:使用模型属性时如何捕捉拼写错误?

[英]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(). 我是JS开发的新手,我发现自己花费了很多精力来解决由模型属性(尤其是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. 在某些情况下,例如由于JS不允许在哈希的左侧使用变量,因此您将无法使用它。 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: 首先,安装插件_super:

https://github.com/lukasolson/Backbone-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). 您的模型应该扩展摘要而不是Backbone.Model(并且应该设置默认值)。

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. 如果您输入的变量名称不正确-应该在开发时的测试中发现它,而不是在运行时进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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