opensas
opensas

Reputation: 63395

Backbone listenTo not working

I have the following working code, and I was planning to replace object.on calls with object.listenTo calls:

setField: function(field) {
  if (this.field) this.field.off(null, null, this);

  if (field) {
    this.field = field;
    this.field.on('validate', this.renderErrors, this);
  }
  return this;
},

and this is the new version

setField: function(field) {
  if (this.field) this.stopListening(this.field);

  if (field) {
    this.field = field;
    this.listenTo(this.field, 'validate', this.renderErrors);
  }
  return this;
},

but some how it's not working. The method this.renderErrors is no being called with the second version.

The strange thing is I updated al the rest of my app accordingly without any trouble.

I'm sure there must be something pretty silly I'm missing.

BTW, this is the code used by the field to raise the event

[...]
  this.trigger('validate', this.errors);

  this.error = !this.isValid();
  return this.errors;
},

Upvotes: 2

Views: 2250

Answers (2)

opensas
opensas

Reputation: 63395

I finally found the cause of the problem

I was destroying the view with the setField method (which released all the events attached to it when using listenTo instead of just object.on).

It was a bug on my own code, so listenTo works ok

Leaving this question open in case someone wants to find an example of how to migrate from observee.on to observer.listenTo

Upvotes: 2

damienc88
damienc88

Reputation: 1977

I haven't used the new listenTo and stopListening yet, but I can see that in your new version, you're calling stopListening against the parameter field, meaning your view is still listening to the previously-visible this.field

setField: function(field) {
    if (this.field) this.stopListening(field);

Your existing version calls off on this.field.

Try using:

if (this.field) this.stopListening(this.field);

Upvotes: 4

Related Questions