ManuelDeLeon / viewmodel

MVVM for Meteor
https://viewmodel.org
MIT License
205 stars 23 forks source link

Detect changes during runtime #217

Closed dnish closed 8 years ago

dnish commented 8 years ago

For example, I want to fire an event if a user likes a message - but this should only happen, if it's happened during the runtime and not if the user reloads the page. So for example, I have this message VM which inherits from a collection:

Template.message.viewmodel({

 message:null,
 liked:false
});

I want to fire the event when the "liked" property changes from false to true, but it should not fire if it's true on the beginning. Normally I would do something like this:

autorun: [
    function() {
      if(this.liked()) { console.log("Event fired...");}
     }
]

...but this will also run on every page reload.

ManuelDeLeon commented 8 years ago

You then need show the events after the user starts the app, not the ones before. I wrote something similar here:

https://forums.meteor.com/t/reactivity-and-triggering-an-event-on-the-other-end-so-to-speak/20087/5?u=manuel

dnish commented 8 years ago

@ManuelDeLeon Just had an idea, as I remembered that you've changed onCreated behavior. What do you think about this?

Template.message.viewmodel({

 message:null,
 liked:false,
 wasLiked:false,

 onCreated() {
  this.wasLiked(this.liked());
  },

 autorun: [

  function() {
    if(this.wasLiked() != this.liked() { console.log("Fire event..."); } 
  }
]
});

On the first test, it seems to work.

ManuelDeLeon commented 8 years ago

I'm sorry but this question is regarding the overall design and structure of your system so I'm not in a good position to give an opinion. I will say that your code has a smell to it (too imperative). It may be symptom of a larger architectural problem.

fvpDev commented 8 years ago

I would do something like

Template.message.viewmodel({

 message:null,
 likes: 0,
 liked: function () { return this.likes() > 0 },

 autorun: [
  function() {
    if(this.liked() { console.log("Fire event..."); } 
  }
]
});
dnish commented 8 years ago

@fvpDev But in this case, it would fire automatically on every page reload, because it inherits the likes from the collection document. So for example, you have a posting which has 4 likes - if the user visits your page, liked() is automatically true and you fire an event (f.e. an animation) which you want to fire only if "a like" happened during the visitors session.

In my example above you copy the "start value" into another variable and check if this one has changed during the visitors session. If yes, the event fires.

fvpDev commented 8 years ago

Oh right, yeah I meant to l leave that onCreated func in there as well. My bad