0

I'm trying to replicate vue.js just for the sake of learning. I do not understand the source code, I'm just going about it my way.

I have a class

class Relidon {
    constructor(data) {
        this.methods = data.methods       
    }
        attributeHandler(node, attr, title){    
                if(title == 'clickDirective'){
                    node.addEventListener('click', function(e){
                        e.preventDefault(e);
                            this.methods.reverseMessage()
                    })
                }
        }
}

That's the framework and then I call it.

new  Relidon({
  el: 'r-app',
  data: {
    message: 'Hello People!',
    age: '29',
    something: 'testing',
    seen: false,
    attrTitle1: 'this is the first title',
    attrTitle2: 'this is the second title',
  },
  methods: {
    app: this,
    reverseMessage: function () {
      console.log(this.data.message)
    }
  }

})

(I removed all the code that deals with everything else so that you can see the real problem)

this in app refers to the window object. How can I make this refer to the object I created?

relidon
  • 2,142
  • 4
  • 21
  • 37
  • In `attributeHandler`, accessing `this` will target the callback scope of the node's event listener. You can change the function to have a fat arrow notation instead to create a lexical this. And what is `this` in `methods.app` suppose to reference? – Shane Aug 15 '17 at 01:12
  • @ShanevandenBogaard I thought `this` in `methods.app` would refer to the entire object `{el: ...}` but it refers to `Window` – relidon Aug 15 '17 at 01:15
  • It would not reference the most outer object when using `this` and `methods.app` is a function, it will reference the `methods` object. You cant create a reference to an object this way. I dont see the usecase of creating a reference to the parent object either. Essentially if you can access `methods`, you can access "app". – Shane Aug 15 '17 at 01:24
  • @ShanevandenBogaard I changed `reverseMessage: function ()` to `reverseMessage:()=>` and `this` refers to the window. I'm way over my head here. The `methods.app` was just for my testing, I would not use that. – relidon Aug 15 '17 at 01:40
  • @ShanevandenBogaard I added `var framework = new Relidon({})` and I knew I can access `framework.data.name` from but I'm trying to understand how vue.js does it without using a variable – relidon Aug 15 '17 at 01:51

0 Answers0