Get information from template after drag with jQuery

74 views Asked by At

I am trying to get the user ID from a photo at the moment I stop dragging it. I am using Meteor with JQueryUI Draggable. As the photos are rendered, I print the user to the console which works fine and gives the unique user ID correctly. When I drag and then stop, however, it returns incorrectly the user ID of the last rendered photo.

I have this html

<template name="Gallery">
    <ul id="gallery-photos">
        {{#each photos}}
            {{> galleryPhoto}}
        {{/each}}
    </ul>
</template>

<template name="galleryPhoto">
    <li>
        <img src=""/>
    </li>
</template>

and this JS

Template.galleryPhoto.rendered = function () {
    var img = this.find('img');

    var user = Meteor.users.findOne({_id: this.data.user});
    console.log(user); //Logs unique user ID for every photo rendered

    var time = this.data.timestamp; // "1431998534049"
    var path = this.data.user + "_" + time + ".jpg";

    img.src = path;

    $('li').draggable({
        axis: "x"
    },
    stop: function () {
        var left = $(this).position().left;
        if(left > 0) {
            $(this).remove();
            console.log(user); //Logs the ID of the last photo created
        }
    }); 
};

Is there any way to get the correct user on drag stop? I am sure the Meteor way of doing this is to involve template events rather than the jQuery callback, but I am still rather inexperienced and not sure how to go about this.

1

There are 1 answers

0
ZuzEL On BEST ANSWER

When you do $('li') each time new image is rendered, you override drag listener of all li elements on your page. To select DOM elements inside template context use this.$('li')

Meteor doc

Off cause you are free to give your li Elements unique ids and do it old school. It's up to you