【问题标题】:Whats the difference between instanceMethods and getterMethods in sequelizejs?sequelizejs 中的 instanceMethods 和 getterMethods 有什么区别?
【发布时间】:2015-12-31 03:17:09
【问题描述】:
sequelize.define("aModel", {
    text: DataTypes.TEXT
}, {
    instanceMethods: {
        getme1: function() {
            return this.text.toUpperCase();
        }
    },
    getterMethods: {
        getme2: function() {
            return this.text.toUpperCase();
        }
    }
});

InstanceMethodsgetterMethods 似乎完成了同样的事情,允许访问虚拟键。为什么要使用一个而不是另一个?

【问题讨论】:

    标签: orm sequelize.js


    【解决方案1】:

    您使用Model.method() 调用的实例方法,但如果您有一个名为text 的getter 方法,它将在您使用instance.text 时调用。同样,当您执行 instance.text = 'something' 时会使用 setter 方法。

    例子:

    var Model = sequelize.define("aModel", {
        text: DataTypes.TEXT
    }, {
        instanceMethods: {
            getUpperText: function() {
                return this.text.toUpperCase();
            }
        },
        getterMethods: {
            text: function() {
                // use getDataValue to not enter an infinite loop
                // http://docs.sequelizejs.com/en/latest/api/instance/#getdatavaluekey-any
                return this.getDataValue('text').toUpperCase();
            }
        },
        setterMethods: {
            text: function(text) {
                // use setDataValue to not enter an infinite loop
                // http://docs.sequelizejs.com/en/latest/api/instance/#setdatavaluekey-value
                this.setDataValue('text', text.toLowerCase());
            }
        }
    });
    
    Model.create({
        text: 'foo'
    }).then(function(instance) {
        console.log(instance.getDataValue('text')); // foo
        console.log(instance.getUpperText()); // FOO
        console.log(instance.text); // FOO
    
        instance.text = 'BAR';
    
        console.log(instance.getDataValue('text')) // bar
        console.log(instance.text); // BAR
    });
    

    【讨论】:

    猜你喜欢
    • 2015-07-12
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    • 2012-02-06
    • 2011-02-25
    • 2011-11-22
    • 2015-03-26
    相关资源
    最近更新 更多