2013-10-17 1 views
8

2 개의 인스턴스 메소드로 간단한 모델을 설정했습니다. 라이프 사이클 콜백에서 이러한 메서드를 어떻게 호출 할 수 있습니까?Sails/Waterline의 lifecycle 콜백에서 모델 인스턴스 메서드를 호출하려면 어떻게해야합니까?

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

, 일반 자바 스크립트에서 함수를 정의 그들과 같이 전체 모델 파일에서 호출 할 수있는이 방법을 시도해보십시오

// 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

해봐요doAnotherThing은 속성이 아니며 메서드이며 Lifecycle 콜백 수준이어야합니다. 이 같은 시도 : 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"문자열. 대신에이 기능을 별도로 실행하려고 시도하고 작동하게 될 것입니다.