Backbone.js的模型属性常数 - 这是很好的做法? [英] Backbone.js model property constants - is this good practice?

查看:112
本文介绍了Backbone.js的模型属性常数 - 这是很好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型实例的属性麻烦跟踪。比如我有声明,如:

I have trouble keeping track of the properties of a Model instance. For example I have declarations such as:

MyModel = Backbone.Model.extend({});

然后在我的意见,我经常做这样的事情:

Then in my views, I'm often doing something like:

var someVal = this.model.get('someProperty');

我开始在一个对象封装在一起,并通过它作为第二个参数到View的构造函数,例如移动搜索的字符串常量到的任务:

I was beginning the task of moving a View's strings into constants by encapsulating them in an object and passing it as a second parameter to a View's constructor, for example:

SchemaOptionsView = Backbone.View.extend(
    { /* Body of View here as usual */}, 
    {
        TEMPLATE: '#View-Template',
        INPUT_REQUIRED:'required'
    });

当我开始思考,我可以用我的模型做这个解决两个问题:

When I got to thinking, I could solve two problems by doing this with my Models:

MyModel = Backbone.Model.extend(
{ /* Body of Model here as usual */},
{
    PROPERTY_1 = 'p1',
    PROPERTY_2 = 'p2'
});

然后我可以使用常量来检索属性值:

I could then use the constant to retrieve the property value:

var someVal = this.model.get(MyModel.PROPERTY_1);

这将让我清楚地看到模型实例中包含的属性,还可以在适当的地方移动的字符串值成一个常量。

This would allow me to clearly see the properties a Model instance contains, and also moves a string value into a constant in an appropriate place.

我还没有看到这个推荐,或以任何例子。我错过了什么?什么人认为这个想法?

I have not seen this recommended or in any examples. Have I missed something? What do people think about this idea?

推荐答案

这是解决非问题。您的模型应该有明确的属性 - 我们使用默认的哈希枚举我们的模型中所有可用的属性。这不仅提供了一个目录,一个模型具有的属性,但它也提供了一种方法来覆盖非验证的输入。

This is solving a non problem. Your models should have well defined attributes - we use the defaults hash to enumerate all the available attributes of our models. Not only does this provide a catalog of the attributes that a model possesses but it also provides a way to override a non-validated input.

这篇关于Backbone.js的模型属性常数 - 这是很好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆