jagi / meteor-astronomy

Model layer for Meteor
https://atmospherejs.com/jagi/astronomy
MIT License
605 stars 66 forks source link

this is undefined in afterInit event #456

Closed Mokto closed 8 years ago

Mokto commented 8 years ago

Hi,

I'm trying to create a transient field as explained here : http://jagi.github.io/meteor-astronomy/#transient-fields

But I'm stuck because this is undefined. A look at my Astronomy class :

import { Meteor } from 'meteor/meteor';
import { Class } from 'meteor/jagi:astronomy';

const Risks = new Mongo.Collection("risks");

const Risk = Class.create({
  name: 'Risk',
  collection: Risks,
  secured: false,
  fields: {
    createdAt: {
       type: Date,
       immutable: true,
       default: new Date()
    },
    riskLabelId: {
      type: String,
      default: ""
    },
    gravityId: {
      type: String,
      default: ""
    },
    exposureId: {
      type: String,
      default: ""
    },
    preventionIds: {
      type: [String],
      default: []
    },
    taskId: String,
    workUnitId: String,
    siteId: String,
    companyId: String
  },
  events: {
    afterInit: function() {
      console.log(this);//undefined
    }
  }
});

export default Risk;

Thanks for your great project, migrating from simple schema is hard but it is worth it ! ;)

joefru commented 8 years ago

Docs for transient fields need updating. See docs for events: http://jagi.github.io/meteor-astronomy/v2#events

Basically, event functions now take parameter for the event object. Try this:

afterInit: function(e) { console.log(e.currentTarget); }

lukejagodzinski commented 8 years ago

Yes I have to update this example in the documentation. It's for version 1.0. Right now you can access document using code presented by @joefru

Mokto commented 8 years ago

Ok thanks !!

So I assume I can do something e.currentTarget.age = 30 ? (to modify the doc when it is initialized)

lukejagodzinski commented 8 years ago

Yes exactly.

afterInit(e) {
  const doc = e.currentTarget;
  doc.age = 30;
}

I've updated also documentation page