Andrew Mao
Andrew Mao

Reputation: 36930

Getting the Meteor template instance for a given DOM element

I'm adding drag-and-drop functionality with jQuery-UI to my Meteor app for templates that were rendered with Meteor. By using the .rendered callbacks for templates, I can set the draggable and droppable widgets just fine.

The trick part is when a drop occurs. jQuery-UI gives an event and an object in the callback: http://api.jqueryui.com/droppable/#event-drop. However, I need to find either the meteor template instances or the underlying collection data ids in order to do something with the draggable and the droppable such as updating a collection, etc.

What's the best way to do this? The closest thing I've seen to anything is in a property called _spark_fooObjectId that seems to have been added by Meteor. But what does that even mean?

enter image description here

My first attempt, based on reading https://github.com/meteor/meteor/wiki/Spark, is to try the following:

drop: (event, ui) ->
  console.log Spark.getDataContext(ui.draggable)

However, this returns null. Any other ideas?

Upvotes: 2

Views: 675

Answers (2)

Cristina Jadi Martins
Cristina Jadi Martins

Reputation: 26

Well, if you want data for the very element you are dragging, one solution might be using the template data to your favor. For instance, you could put a field named "label" in your Mongo documents and wrap your draggable content in a div like this one:

{{#each yourHelper}}
  <div id={{label}}> 
    the rest of your content
  </div>
{{/each}}

And then, if, for example, you wanted to get another field from the same document in the DB, your JS would look like:

 var myquery = $(event.target).parents("div").attr("id");

console.log(myCollection.findOne({"label":myquery}).anotherField);

The same thing applies if you prefer to use a child, only you'd use find() instead of parents().

Upvotes: 0

Andrew Mao
Andrew Mao

Reputation: 36930

Oops, that was just a slight oversight. The right solution is

Spark.getDataContext(ui.draggable.context)

since ui.draggable is a jQuery object.

Upvotes: 0

Related Questions