2
votes

In a backbone model, is it possible to trigger an event in the initialize function, for a nested view? I based my current code off this example: https://stackoverflow.com/a/8523075/2345124 and have updated it for backbone 1.0.0. Here is my initialize function, for a Model:

var Edit = Backbone.Model.extend({
    initialize: function() {
        this.trigger('marquee:add');

        this.on('change', function(){
            this.trigger('marquee:add');
        });
    }
    ...
}

I'm trying to call a method renderMarquee when the model is initialized:

var EditRow = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, "change", this.render);   // works
        this.listenTo(this.model, "marquee:add", this.renderMarquee);  // only called when changed, but not when initially created
    ...
}

renderMarquee IS called when the model is changed, but not when it is initialized. 'change' events work as expected (this.render is called). Any thoughts?

Thanks!

2

2 Answers

0
votes

This doesn't make a lot of sense because you are initializing the model somewhere prior to doing the view.listenTo call. Unfortunately, you don't really have a choice in that matter.

You are probably going to want to move the event handling to a Backbone.Collection which already has built in events you can listen on for adding/removing.

1
votes

I am currently facing a similar problem. I needed to trigger the change event in the initialize method of my model. I looked into the backbone code which revealed why this is not happening:

var Model = Backbone.Model = function(attributes, options) {
    ...
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments); 
  };

the set is executed before the initialize and this.change is emptied setting the model state to "nothing has changed".

In order to overwrite behavior this I added the following code to my initialize method.

initialize: function(attributes, options) {
  ...
  this.changed = attributes;
  this.trigger('change');
  for (attr_name in attributes) {
    this.trigger('change:' + attr_name);
  }
},

I trigger all change events manually, this is important for me since inheriting models may bind to change or change:attrxy. But this is not enough, because if I just trigger the events the changedAttributes() method would return false therefore I also set this.changed to the current attributes.