0

I have a checkbox with class js-map-source in my HBS template. I am listening clicks on this checkbox in Marionette view. This part is working correctly - when I click on checkbox I am able to console.log checkbox status.

Code:

module.exports = Marionette.ItemView.extend({
  # something else....

  ui: {
    mapSource: '.js-map-source'
    # something else...
  },

  events: {
    'click @ui.mapSource': 'mapSourceChanged'
    # something else...
  }

  # something else...

  mapSourceChanged: function (event) {
    var switchStatus = $(this.ui.mapSource).is(":checked");
    console.log(`TypeOf: ${typeof switchStatus}; value: ${switchStatus}`);
  },
}

So let's click few times. Following logs appers in console:

TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false
TypeOf: boolean; value: true
TypeOf: boolean; value: false`

That was expected behaviour.

The problem occurs when I am trying to save this checkbox value (true/false) in my model. Let's add this.model.set('source', switchStatus) to the function mapSourceChanged.

Now I have to double click checkbox to mark is as checked (visually). But still, I can uncheck checkbox with one click.

Code:

module.exports = Marionette.ItemView.extend({
  # something else....

  ui: {
    mapSource: '.js-map-source'
    # something else...
  },

  events: {
    'click @ui.mapSource': 'mapSourceChanged'
    # something else...
  }

  # something else...

  mapSourceChanged: function (event) {
    var switchStatus = $(this.ui.mapSource).is(":checked");
    console.log(`TypeOf: ${typeof switchStatus}; value: ${switchStatus}`);
    this.model.set('source', switchStatus);
  },
}

Logs:

2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true
TypeOf: boolean; value: false
2TypeOf: boolean; value: true

This 2 on the beginning of the line means that I get the same log again.

What is the reason for this behaviour? How to fix it?

3
  • bit tricky to say from this code - maybe log out your event also as it's most likely a change on the model triggering an event you have the view listening for - logging our the event will give you something to work from Jun 24, 2018 at 14:35
  • Are you using any data binding library/is your input wrapped in a label?
    – T J
    Jul 3, 2018 at 10:22
  • I figured it out. I had an event listener, set on model change. Thank you, guys. Jul 4, 2018 at 17:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.