【问题标题】:Meteor Autoform `this.field("keyName").value` returns undefined in SchemaMeteor Autoform `this.field("keyName").value` 在 Schema 中返回未定义
【发布时间】:2016-03-14 16:54:32
【问题描述】:

我有一个Person,我希望在某人更改其firstNamelastName 字段时自动创建一个fullName 字段和值。

People.attachSchema(new SimpleSchema({
    firstName: {
        type: String,
        optional: false,
        label: 'First Name'
    },
    lastName: {
        type: String,
        optional: false,
        label: 'Last Name'
    },
    fullName: {
        type: String,
        optional: false,
        label: 'Full Name',
        autoValue: function() {
          var firstName = this.field("firstName");
          var lastName = this.field("lastName");

          if(firstName.isSet || lastName.isSet){
                return firstName.value + " " + lastName.value;
            } else {
                this.unset();
            }
          }
    }
}));

如果我这样做

People.update("ZqvBYDmrkMGgueihX", {$set: {firstName: "Bill"}})

fullName 设置为Bill undefined

我做错了什么?

【问题讨论】:

    标签: meteor meteor-autoform meteor-collection2 simple-schema


    【解决方案1】:

    现在,您的条件firstName.isSet || lastName.isSet 表示,如果firstNamelastName 在文档中可用,则创建fullName。所以它正确地分配了全名,因为其中一个已设置(名字设置为比尔)。您需要像这样使用&& 而不是||

    People.attachSchema(new SimpleSchema({
        firstName: {
            type: String,
            optional: false,
            label: 'First Name'
        },
        lastName: {
            type: String,
            optional: false,
            label: 'Last Name'
        },
        fullName: {
            type: String,
            optional: false,
            label: 'Full Name',
            autoValue: function() {
                var firstName = this.field("firstName");
                var lastName = this.field("lastName");
    
                if(firstName.isSet && lastName.isSet){
                    return firstName.value + " " + lastName.value;
                } else {
                    this.unset();
                }
            }
        }
    }));
    

    但是,根据您的问题,我认为,您只想在firstNamelastName 之一更新时设置fullName,我认为(我不确定),您需要检查@987654331 @检查当前操作中是否为$set

    【讨论】:

    • 太棒了,成功了。我对this.field("someField") 实际指的是什么感到有些困惑。将对象插入People 时,仅设置firstNamelastName。那么this.field("firstName") 是否总是在任何类型的CreateUpdate 操作期间引用该值?
    • @fuzzybabybunny 是的,this.field("firstName").value 始终是指该值,无论是在当前操作期间还是之前的操作期间设置。
    • 嗯,好的,所以autoValue 中的函数不需要某种触发器/事件来运行?
    • @fuzzybabybunny autoValue 将在您的架构为 cleaned 时运行。清理将在UpdateInsert 之前自动完成,或者您可以通过显式调用来清理它。
    猜你喜欢
    • 2016-06-19
    • 2015-10-25
    • 2014-07-21
    • 1970-01-01
    • 2015-03-05
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多