如何在骨干中创建新集合之前验证集合中是否存在属性?

时间:2014-07-08 20:57:06

标签: backbone.js

我正在学习骨干,并且有一个非常简单的应用程序来创建联系人列表。到目前为止,我有名字,姓氏和电子邮件地址。我想创建一个验证,以便在创建新邮件之前检查集合中是否已存在电子邮件地址。这就是我创建集合的方式。

  this.collection.create({
            FirstName: this.first_name.val(),
            LastName: this.last_name.val(),
            Email: this.email_address.val()
        },
        {
            wait: true,

            success: function (resp) {
                console.log('successfully saved to the database');
            },
            error: function (errors) {
                console.log('email address exists');
            }
        });

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

如果集合中必须唯一的主要内容是电子邮件地址,您可以“摘取”电子邮件地址,并确保没有返回与您要添加的新电子邮件地址相匹配的电子邮件地址。

var emails = this.collection.pluck("Email")
if(!_.contains(emails, targetEmailAddress)
{ 
    //you have a new email address so go ahead and create the model
}