Search code examples
javascriptbackbone.jsbackbone-views

What is the purpose of the _createElement method?


I am studying Backbone.js (ver 1.3.3).

There's a line like below in Backbone.View (line 1441)

_createElement: function(tagName) {
  return document.createElement(tagName);
},

Why Backbone.View has _createElement(tagName) method instead of using 'document.createElement(tagName)' directly.


Solution

  • When you're developing a library that will be used in different projects, ones that you can't even imagine, you have to encapsulate everything and provide easy ways to override every specifics of it. That's what Backbone's devs have done.

    Now imagine a programmer using Backbone that don't want to use document.createElement and instead, he wants to create nodes in his own structure. Then, his BaseNodeView could override _createElement to handle that:

    var BaseNodeView = Backbone.View.extend({
        _createElement: function(tagName) {
            return NodeFactory.create(tagName);
        },
    });
    

    That's exactly what it's for and it's written in the comments just above.

    Produces a DOM element to be assigned to your view. Exposed for subclasses using an alternative DOM manipulation API.

    The function is used within the view code abstracting what's really happening behind, leaving it up to you to decide if the default behavior is wanted.

    Some of Backbone's API are not documented and it's needed to dive into the source to find every ways it can be hooked into.