0

I am trying to validate a field in a single component using ember-validations but giving the possibility of passing a validations object to the component instead of hardcoding it inside. This code:

EditDefaultPropertyComponent = Ember.Component.extend EmberValidations.Mixin,

validations:
  value:
    numericality: true

onValueObserver: Ember.observer('value', ->
  @validate()
    .then(() =>
      ...
      console.log 'good'
      @set 'error', null
    )
    .catch((err) =>
      ...
      console.log 'bad'
      @set 'error', err
    )
  )

setupFlags: (->
  ...
).on('init')

Will work just fine, but if I want to setup at component's initialization time the validations object with some arbitrary validation passed as a parameter to the component, say for example in setupFlags:

  setupFlags: (->
    @setProperties(
        ...
        @set 'validations', Ember.copy ( { value: { numericality: true }}))
).on('init')

Won't work. It will always print "good" no matter the input. If I access

console.log (@get 'validations')

inside the then() branch of the @validate method it shows however the object. Am I missing some control flow here?

Urco
  • 365
  • 3
  • 14

2 Answers2

0

Ok, I already know the answer but I don't know how to overcome it. I'll put it here in the case someone finds it out.

The EmberValidations.Mixin added to the component incorporates an init method that will check if there is any validations object defined and will add an observer to each one of it's properties. That code is run before the init function of the component, hence, when the validations object is modified in the component the observers are already set up on the values the mixin encountered previously.

Urco
  • 365
  • 3
  • 14
0

Ok, solved.

You can define an init method in the mixin that will override it's own init method, run some code, and then call the super() constructor.

init: ->
  ...
  @_super()
Urco
  • 365
  • 3
  • 14