使用 jQuery 拖动后从模板获取信息

Get information from template after drag with jQuery

我试图在停止拖动照片时从照片中获取用户 ID。我将 Meteor 与 JQueryUI Draggable 一起使用。在呈现照片时,我将用户打印到控制台,该控制台工作正常并正确提供了唯一的用户 ID。但是,当我拖动然后停止时,它 returns 错误地使用了最后渲染照片的用户 ID。

我有这个html

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

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

和这个 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
        }
    }); 
};

有没有办法让正确的用户停止拖拽?我确信 Meteor 这样做的方法是涉及模板事件而不是 jQuery 回调,但我仍然相当缺乏经验,不确定如何去做。

当您在每次呈现新图像时执行 $('li') 时,您会覆盖页面上所有 li 元素的拖动侦听器。对于模板上下文中的 select DOM 元素,使用 this.$('li')

Meteor doc

关闭因为您可以自由地给您的 li 元素独特的 ids 并按照老派的方式进行。由你决定