Attempting to bind a callback by passing in a function causes an error

I just want to fire an event when input changes the value using jQuery 1.7.2 and Backbone.js.

I currently have the following (which works)

MyView: Backbone.View.extend({
  initialize: function() {

    this.colorInput = $("<input />", {
         "id": "color",
         "name": "color",
         "value": this.model.get("color")
    });

    var self = this;
    this.colorInput.on("change", function() {
      self.changeColor();
    });

  },
  changeColor: function() {
    var color = this.colorInput.val();
    this.model.set("color", color);
  }
});

I tried to do it in a different way when I just pass in my function.

this.colorInput.on("change", this.changeColor, this);

But when you try to do it this way, it throws an error

((jQuery.event.special [handleObj.origType] || {}). handle || handleObj.handler) .apply is not a function
.apply (matched.elem, args);

( line 3332 )

Which I can’t understand. Any ideas why this method is not working?

+5
source share
2 answers

jQuery on:

.on( [, ] [, ], (eventObject))
.on(- [, ] [, ])

Backbone on:

object.on(, , [])

, jQuery - . , jQuery on handler(eventObject) , , .

:

MyView: Backbone.View.extend({
  events: {
    'change input': 'changeColor'
  },
  initialize: function() {
    this.colorInput = $("<input />", {
       "id": "color",
       "name": "color",
       "value": this.model.get("color")
    });
  },
  render: function() {
    this.$el.append(this.colorInput);
    return this;
  },
  changeColor: function() {
    var color = this.colorInput.val();
    this.model.set("color", color);
  }
});

Backbone .

+11

, . , , , , , .

$('#modal').on('click', function(e) {
   // Execute invalid code here.
});

:

$('#modal').on('click', function(e) {
   // Execute valid code here.
});

, , , , jQuery , , .

, , , , , .

+3

All Articles