Search code examples
backbone.jsbackbone-viewsbackbone-events

Backbone template not changing


I have a view with an event.

events: {
    'click button.add-prediction': 'addPrediction'
},
addPrediction: function(event) {
    var currentPredictions = this.model.get('count');
    this.model.set('count', currentPredictions + 1);

    this.$el.find('.add-prediction').html('predicted').addClass('selected');
},

Doing this:

this.$el.find('.add-prediction').html('predicted').addClass('selected');

doesn't seem the proper way, but when I do,

$(event.target).html('predicted').addClass('selected');

The DOM is not updated, why? What m I doing wrong?

Here is the complete view.

Event.Views.PredictionsView = Backbone.View.extend({
tagName: 'div',
className: 'stats',
events: {
    'click button.add-prediction': 'addPrediction',
    'click button.add-prediction.selected': 'removePrediction'
},
initialize: function() {
    this.model.on('change', this.render, this);
},
removePrediction: function() {
    var currentPredictions = this.model.get('count');
    this.model.set('count', currentPredictions - 2);

    this.$el.find('.add-prediction').html('Predict').removeClass('selected');
    this.$el.removeClass('selected');
    this.$el.parent().find('.add-prediction').removeAttr('disabled');
},
addPrediction: function() {
    var currentPredictions = this.model.get('count');
    this.model.set('count', currentPredictions + 1);

    this.$el.find('.add-prediction').html('Remove prediction').addClass('selected');
    this.$el.addClass('selected');
    this.$el.parent().find('.add-prediction:not(.selected)').attr('disabled', 'true');

},
setTemplate: function() {
    var that = this;
    $.get('templates/singleEvent/team-details.html', function(data) {
        that.template = _.template(data);
        that.render();
    }, 'html');
    return this;
},
render: function() {
    var eventTemplate = this.template(this.model.toJSON());
    $(this.el).html(eventTemplate);
    return this;
}

});

Unfortunately I cant make a jsFid, because its too complex and to make it work would take a long time. Thank you.


Solution

  • event.target don't refer button.

    event.target[0] refers button.

    try to

    $(event.target[0]).html('predicted').addClass('selected');
    

    or

    event.target.html('predicted').addClass('selected');