Search code examples
javascriptjquerynode.jsmeteor2-way-object-databinding

Meteor two-way binding - UI update


I have page which is basically rows of div elements. I create those div elements from an array. Each object in the array is a map that has a key username. Here's an example of the

{{#each rows}}
      <div class="col-md-1 poolbox">{{this.username}}</div>
{{/each}}    

When the page loads, it successfully grabs whatever the value of this.username is. I have a click event on that div so that it when it's clicked, I create a document in mongo and would also like to update the value in map to the new value.

'click .divbox': function(e, t) {
    //alert("You Clicked " + JSON.stringify(this));
  Box.insert({
    username: 'NEW VALUE',        
    createdAt: new Date()
  });

Once it's pushed to the database, I would like to update the value of username in the map to a new value which should affectively change the value in the UI. I tried doing this.username = "NEW VALUE"; after I push it the the DB but that didn't work.

Eventually I would like to do pub/sub so that it pulls from the database all the time.


Solution

  • you can actually change the value just add a helper with your rows array and check if username has changed.

    Example

    js

    Template.home.helpers({
      rows : function(){
        var rows = [{username :'abc'},{username :'abd'},{username :'ab'}];
        _.each(rows,function(value,key) {
          if(Box.find({old_username : value.username}).count() > 0){
            rows[key].username = Box.find({old_username : value.username}).fetch()[0].username;            
          }
        })       
        return rows;
      }
    })
    
    
    
    Template.home.events({
     'click .poolbox': function(e, t) {
        var current_username = 'NEW VALUE';
        Box.insert({
          username: current_username,        
          old_username : $(e.currentTarget).text(),
          createdAt: new Date()
        });
      }
    })
    

    and in your html

    {{#each rows}}
      <div class="col-md-1 poolbox">{{username}}</div>
    {{/each}}