David Mckee
David Mckee

Reputation: 1180

Add event to database on user click in Meteor

I am trying to update an collection in Meteor when a user clicks on a certain link. The link opens up a new tab, which is on an external site. However, I want to store this click in my database.

I have tried using e.preventDefault(), but then I can't get the link to open in a new tab. Any suggestions?

Upvotes: 0

Views: 187

Answers (3)

Tarang
Tarang

Reputation: 75965

You ought not to use javascript to open the new tab since this will activate the popup blocker. The best solution is to have a link, as normal, and track the link on the side:

Html:

<template name="link">
    <a href="http://google.com" target="_blank" id="the_link">CLick</a>
</template>

JS:

Template.link.events({
    'click a#the_link': function(e,tmpl) {
        MyCollection.update({_id: "the_link_id"} , {$inc { "clicks":1 } });
    }
});

Upvotes: 1

sitaram9292
sitaram9292

Reputation: 171

You can do the insertion in the server side which is secure. The window can be opened in the success of the response.

In Client

Template.name.events{(
 "click .clickevent":function(e){

   e.preventDefault();
       Meteor.call("Methodname", datatoinsert,function(err){
       if(!err)
        window.open(url, '_blank');                
      })   
       }    

  )};

In Server

Meteor.methods({
Methodname:function(datatoinsert){

  Tablename.insert({
  //insert data here
   })    
  }
 }); 

In this way you can add event and on successful data insert you can open a window.

I hope it helps you.

Upvotes: 0

rgoomar
rgoomar

Reputation: 184

You can use a click event and use a window.location after inserting into the database. So, it would look something like this:

Template.name.events({
  'click a' : function(e) {
    e.preventDefault();
    // Insert data into database
    Table.insert({
      // data here
    });
    // Open new tab
    window.open(url, '_blank');
  }
});

Upvotes: 1

Related Questions