HelloWorld
HelloWorld

Reputation: 11247

Initialize property in Collections

I am currently learning backbone and am trying to wrap my head why an initialize function is needed Views and collections?

Here is some of my code:

Tasks = Backbone.Collection.extend({
    //This is our Task collection and holds our Task models
    initialize: function (models, options) {
        console.log(options);

      this.bind("add", options.view.addTaskListeners);
      console.log(this.bind("add", options.view.addTaskListeners));
      //Listen for new additions to the collection.
    }
  });




  //master view


  AppView = Backbone.View.extend({
    el: $("body"),
    initialize: function () {
      this.tasks = new Tasks( null, { view: this });
      // Create a task collection when the view is initialized.
      // Pass it a reference to this view to create a connection between the two
    },
    events: {
      "click #add-task":  "showPrompt",
    },

The creator of the tutorial decided to use this 'initialize' property, but initialize is never used as a property such as Tasks.initialize or AppView.initialize. I tried changing the name of the property but it does not work. Is this a reserved word or key word in backbone? Why is it needed? Thanks!

Upvotes: 0

Views: 33

Answers (1)

David Sulc
David Sulc

Reputation: 25994

Initialize is a special function (i.e. "reserved"). If it is defined on a view/model/collection, it will be executed when the view/model/collection is instanciated (i.e. when you call new). So if you change its name, it won't be called automatically by Backbone anymore...

Upvotes: 1

Related Questions