2013-10-17 7 views
8

私は2つのインスタンスメソッドで単純なモデルを設定しました。これらのメソッドをライフサイクルコールバックでどのように呼び出すことができますか?Sails/Waterlineのライフサイクルコールバックでモデルインスタンスメソッドを呼び出すにはどうすればよいですか?

module.exports = { 

    attributes: { 

    name: { 
     type: 'string', 
     required: true 
    } 

    // Instance methods 
    doSomething: function(cb) { 
     console.log('Lets try ' + this.doAnotherThing('this')); 
     cb(); 
    }, 

    doAnotherThing: function(input) { 
     console.log(input); 
    } 

    }, 

    beforeUpdate: function(values, cb) { 
    // This doesn't seem to work... 
    this.doSomething(function() { 
     cb(); 
    }) 
    } 

}; 

答えて

2

カスタム定義されたインスタンスメソッドは、ライフサイクルで呼び出されるようには設計されていませんが、モデルをクエリした後にデザインされているようです。

SomeModel.findOne(1).done(function(err, someModel){ 
    someModel.doSomething('dance') 
}); 

ドキュメントの例へのリンク - https://github.com/balderdashy/sails-docs/blob/0.9/models.md#custom-defined-instance-methods

+0

これはあなたがそれを行う方法を説明していません。彼らは本当に私が心配している限りこれを構築しておくべきです、それは超常用のケースです。 – light24bulbs

2

、通常のJavaScriptで関数を定義し、彼らがこのような全体のモデルファイルから呼び出すことができますこの方法試してみてください:

// Instance methods 
function doSomething(cb) { 
    console.log('Lets try ' + this.doAnotherThing('this')); 
    cb(); 
}, 

function doAnotherThing(input) { 
    console.log(input); 
} 

module.exports = { 

    attributes: { 

    name: { 
     type: 'string', 
     required: true 
    } 
    }, 

    beforeUpdate: function(values, cb) { 
    // accessing the function defined above the module.exports 
    doSomething(function() { 
     cb(); 
    }) 
    } 

}; 
+0

もう少し年をとっていたことに気付きました。 – danba

1

をdoSomethingのdoAnotherThingは属性ではなく、メソッドであり、ライフサイクルコールバックレベルでなければなりません。このような何か試してみてください:2位で

module.exports = { 

    attributes: { 

     name: { 
      type: 'string', 
      required: true 
     } 

    }, 

    doSomething: function(cb) { 
     console.log('Lets try ' + "this.doAnotherThing('this')"); 
     this.doAnotherThing('this') 
     cb(); 
    }, 

    doAnotherThing: function(input) { 
     console.log(input); 
    }, 

    beforeCreate: function(values, cb) { 

     this.doSomething(function() { 
      cb(); 
     }) 
    } 

}; 

を、あなたは(「本」)をthis.doAnotherThingをコンソールに送信しようとしているが、あなたは上のパラメータと同様にそれを渡すことはできませんので、それはモデルのインスタンスであります"Lets try"文字列。その代わりに、この機能を別に実行しようとすると、動作します

関連する問題