【问题标题】:Custom fields in backbone model not defined when used in collection在集合中使用时未定义骨干模型中的自定义字段
【发布时间】:2013-03-26 11:33:35
【问题描述】:

我在 Backbone 中定义了一个模型和集合,如下所示:

$(document).ready(function () {

DeviceModel = Backbone.Model.extend({
    urlRoot: '/ajax/mvcDevices',

    validationRules: {
        name: [{ rule: 'required'}],
        mac: [
        { rule: 'required' },
        { rule: 'isMacAddress' }
        ],
        speed: [{ rule: 'required'}]
    },

    preprocess: {
        name: ['clean', 'trim'],
        speed: ['clean', 'trim']
    }
});

DeviceCollection = Backbone.Collection.extend({
    url: '/ajax/mvcDevices',
    Model: DeviceModel
});
});

但是,当在 Collection 中使用这些模型时,列出的自定义字段都没有定义。我在这里错过了什么?

【问题讨论】:

  • Model : DeviceModel => model : DeviceModel ? (小写m
  • @WiredPrairie (facepalm) 就是这样,一直盯着我的脸。非常感谢。

标签: javascript backbone.js collections model


【解决方案1】:

您可以使用defaults Model 属性来强制执行默认值,如下所示:

var DeviceModel = Backbone.Model.extend({
    urlRoot: '/ajax/mvcDevices',

    defaults: {
        validationRules: {
            name: [{ rule: 'required'}],
            mac: [
            { rule: 'required' },
            { rule: 'isMacAddress' }
            ],
            speed: [{ rule: 'required'}]
        },

        preprocess: {
            name: ['clean', 'trim'],
            speed: ['clean', 'trim']
        }
    }
});

var DeviceCollection = Backbone.Collection.extend({
    url: '/ajax/mvcDevices',
    Model: DeviceModel
});

var collection = new DeviceCollection();

var model = new DeviceModel({id: 1});
collection.add(model);
console.log(collection.get(1).get('validationRules'));
console.log(collection.get(1).get('preprocess'));

根据 Backbone 文档,如果您使用 new 运算符创建模型,defaults 中的所有属性都将被复制到新对象,因此这取决于您创建模型对象的方式。

【讨论】:

  • 啊..这里的问题是这些值不是数据项,所以我不希望它们进入模型属性并发送到服务器等。它们是验证的支持数据处理模型的代码。
  • @Nidonocu:在这种情况下,您声明它们的方式是正确的,它们应该作为可访问的“标准”实例属性提供,例如 modelInstance.attribute(例如 modelInstance.validationRules)。换句话说,不要通过 Backbone.Model 的 get() 访问它们。
猜你喜欢
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
相关资源
最近更新 更多