dimanche 29 juillet 2018

Backbone's checkbox toggle

I have a checkbox(es) and I am trying to change a bool field of a model when a click event happens.

My HTML checkbox:

<input class="toggle" type="checkbox" >

My model-view JS:

app.SampleView = Backbone.View.extend({

    tagName:  'li',

    template: _.template($('#item-template').html()),

    events: {
        'click .toggle:checkbox': 'toggleChecked'
    },

...

    toggleChecked: function (e) {
        var $target = $(e.target);
        var selected = $target .is(':checked');
        this.model.save({
            isChecked: selected
        });
    },
})

This is the current behavior: The checkbox and the value of the field in the model are false too. When I click once to the checkbox then the value of the "isChecked" field will be true which is good but it doesn't apply any change on the screen (checkbox looks unchecked). When I click to the checkbox second time, then the value of the "isChecked" is still true, and now finally the checkbox looks checked. When I click to the checkbox third time, then the value of the "isChecked" is false, and the checkbox looks unchecked which is also good.

Maybe there is a better way to connect the fields in backbone but I'm quite new with this framework. Thank you for any help!




Aucun commentaire:

Enregistrer un commentaire