Search code examples
javascriptjquerybackbone.js

Unable to change the tagName of model in Backbone


I am trying to set the tagName for the model I am creating but it not working. There is no errors in the console and it works but the tag is div without any class, id or attribute that is specified in the model.

Please help.

jQuery(document).ready(function($) {

  // NOTE: Basic Model of template
  var ZcoBuilderModel = Backbone.Model.extend({
    tagName :  "span",
    className: "zco_builder_element",
    id : "1233",
    attributes : {
      "data-type": "template"
    },
    defaults: {
      en_header: false,
      en_title: false,
      en_Content: false,
      en_Footer: false,
      en_deletable: false,
      title: "",
      en_template_status: false,
      id_header : 0,
      id_title: 0,
      id_Content: 0,
      id_Footer: 0,
    },
    initialize: function() {
      console.log("Created");
    }
  });

  // NOTE: Collaction of templates
  var ZcoBuilderCollection = Backbone.Collection.extend({
    model: ZcoBuilderModel
  });

  // NOTE: View template for Single Model
  var ZcoBuilderView = Backbone.View.extend({
    render: function() {
      var zcoBuilderTemplate = _.template($('#zcoTemplate').html());
      var zcoBuilderTemplateHTML = zcoBuilderTemplate(this.model.toJSON());
      this.$el.html(zcoBuilderTemplateHTML);
      return this;
    }
  });

  // NOTE: View Template for Collection Model this will render above
  var ZcoBuilderViewCollection = Backbone.View.extend({
    render: function() {
      var self = this;

      this.model.each(function(e) {
        var n = new ZcoBuilderView({
          model: e
        });
        self.$el.append(n.render().$el);
      });
    }
  });

 // NOTE: defaults collection
  var zcoBuilderDefaults = new ZcoBuilderCollection(
    [
      new ZcoBuilderModel({
        title: "Global"
      }),
    ]
  );

  //Templates Rendering
  var zcoBuilder = new ZcoBuilderViewCollection({
    el: '#zco_list',
    model: zcoBuilderDefaults
  });
  $('#zco_list').html(zcoBuilder.render());


});

Solution

  • Properties like tagName, id, className, el, and events have a special meaning when using in a View, but there are useless for the Model

    Move it from ZcoBuilderModel to ZcoBuilderView