最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - BackboneJs: In a view whats the difference between el: and tagName: - Stack Overflow

programmeradmin3浏览0评论

I'm trying to wrap my head around this concept.

Can you dumb this down for me and maybe provide a simple example of the difference between the el: attribute and the tagName: attribute?

In some examples, different views use el: sometimes and others use tagName:.

I'm specifically messing around with my own implementation of this example

I'm trying to wrap my head around this concept.

Can you dumb this down for me and maybe provide a simple example of the difference between the el: attribute and the tagName: attribute?

In some examples, different views use el: sometimes and others use tagName:.

I'm specifically messing around with my own implementation of this example

Share Improve this question asked Sep 15, 2011 at 14:30 Mike FieldenMike Fielden 10.2k14 gold badges60 silver badges100 bronze badges 1
  • 1 el will reference to existing elements in our DOM, while tagName we will create a new dom element with the tagName with className if given. – STEEL Commented Feb 28, 2014 at 11:40
Add a ment  | 

2 Answers 2

Reset to default 17

The difference is this:

el should be used to preserve a reference to the actual DOM node representing the view as a whole.

This means you can easily perform actions on it with jQuery or w/e. $(this.el).hide() or $(this.el).html('I am a Jquery Object now');

TagName is only a string that is used to determine the type of DOM node el will be. The default is div, but if you wanted, you could make it any HTML element you please.

Consider:

var view = Backbone.View.extend({
    tagName: 'p',
    initialize: function () {
        _.bindAll(this, 'render');
    },
    render: function() {
        $(this.el).html('I am a jQuery-ized paragraph');
        return this;
    }
});


$(document.body).append(new view().render().el);

The problem you might be running into is that sometimes you set el on the instantiation of a view, in which case the tagName is irrelevant:

var myView = new view({ el: $("someExistingEl") });
var View = Backbone.View.extend({
  tagName: 'span',
  id: 'identity',
  class: 'classy',
  el: $(this.tagName), // or
  el: $('<' + this.tagName + ' />', {
    id: this.id,       // identity
    'class': this.class  // classy
  })  // this is jQuery shorthand for building an element fyi
});

var view = new View();

I think that should work fine.

发布评论

评论列表(0)

  1. 暂无评论