user2602152
user2602152

Reputation: 797

Native 'change' event when using Select2 in Meteor.js?

I am using the select2 package from atmosphere in my Meteor.js-project. I am however unable to get the native 'change' to my event-handler in the template. I need this to access the object context in the template.

This does not fire when changing the select value in a Select2-select box:

Template.myTemplate.events({
    'change .newValue' : function () {
        console.log("I am not fired :(");
        console.log("But I can access this. :)", this);
    }
}

This, however, does work. The only problem is that I can't access the "this" context from the template, which is what I need.

Template.myTemplate.rendered({
    var self = this.data;
    $('.newValue')
    .select2()
    .on('change', function () {
        console.log("I am fired! :)");
        console.log("I can access self, and get the currently logged in user", self);
        console.log("But that is not what I want. :(");
    }
}

Upvotes: 0

Views: 1314

Answers (1)

emgee
emgee

Reputation: 1234

Select2 rewrites the <select> tag into a series of <div>s, so you don't actually have a change event for the native event handler to grab.

What you could do is stash the _id property of your template data in the id of your select2 element. Your select2 on change listener passes a jQuery event and using it's target you can recreate the missing context. It's ugly but works.

Edit:

What I mean is put the Mongo document _id into the html element id field, like so:

template.html

//...

{{#each dropdown}}
  <select id="{{_id}}" class="select2">
    {{#each options}}<option value="{{ serialNo }}">{{ name }}</option>{{/each}}
  </select>
{{/each}} 

//...

template.js

Template.template.rendered = function () {
  $('select2').select2({ 
    // ...
  }).on('change', function (e) {
    console.log(e.target);
  });

// ...

Template.template.dropdown = function () {
  return Dropdowns.find();
}

Assuming your dropdown document was something like:

{
   "_id" : "7MzpRfzyCDTgz4QXJ",
   "name" : "dropdown1",
   "options" : [
                 { 
                   "serialNo" : 1,
                   "name"     : "Option 1"
                 } , {
                   "serialNo" : 2,
                   "name"     : "Option 2"
                 }
               ]
} 

Upvotes: 1

Related Questions