dalgard / meteor-viewmodel

Minimalist VM for Meteor
24 stars 2 forks source link

Do you know about 'this' inside helpers & events? #25

Closed comerc closed 8 years ago

comerc commented 8 years ago
template(name='main')
  +test(a=1)

template(name="test")
  = test
  = a
  = b
  = c
  button#test test
Template.test.onCreated ->
  Template.currentData().b = 2

Template.test.helpers
  test: ->
    @.c = 3
    console.log '@ inside helper', @ # {a: 1, b: 2, c: 3}

Template.test.events
  'click #test': ->
    console.log '@ inside event', @ # {a: 1, b: 2, c: 3}

It is simple vs Template.instance().viewmodel.myValue().

I propose to implement two way binding via this feature.

comerc commented 8 years ago
Template.test.onCreated ->
  Template.currentData().b = 2

It is wrong way, because on next call of +test(a=1) current data will be rewrited.

Workaround. I use "init" helper:

Template.test.helpers
  init: ->
    @.b = 2
  # ...
template(name="test")
  = init
  // ...
comerc commented 8 years ago

https://viewmodel.org/docs/viewmodels#events

Sometimes you need to get your hands dirty and add an event listener. You can do so with the event property. The context (this) is the current view model.

It is solution for true 'this' inside events (and helpers).