What's the difference between initialize and constructor on a backbone model

后端 未结 2 1044
攒了一身酷
攒了一身酷 2020-12-12 23:43

What\'s the difference between initialize and constructor on a backbone model.

When I extend a backbone model (ParentModel) I use the initialize method to set any de

相关标签:
2条回答
  • 2020-12-12 23:56

    constructor is the function that Backbone uses to set itself up - creating the models, setting events, and doing all kinds of other setup. Be very careful about overriding this, because if you prevent Backbone code from running by overriding or shadowing the method, you'll get weird errors that are hard to debug.

    initialize on the other hand is a function that Backbone calls on its objects once it's finished up with its internal plumbing. If you're not doing anything that's specifically intended to interfere with normal Backbone functionality, just use initialize.

    If you're using CoffeeScript, it might be more intuitive to use constructor. (It is for me). Just make sure you always call super, though.

    0 讨论(0)
  • 2020-12-12 23:58

    constructor runs before Backbone sets up the structure. initialize is called inside the structure's constructor function. So basically if you need to augment anything before Backbone sets up the structure, use constructor if you need to augment anything after Backbone sets up the structure use initialize.

    (from a Github discussion on the subject)

    0 讨论(0)
提交回复
热议问题