dimanche 24 juin 2018

I have to double click checkbox to change it's status in Marionette ;/

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?




Aucun commentaire:

Enregistrer un commentaire