首页 > backbone 视图里面的tagName的作用

backbone 视图里面的tagName的作用

请问backbone 中 tagName,el ,className 的作用分别是什么啊? 在什么时候需要用到呢?


如果你指定了 el,那么,this.$el 将指定你设定的元素,el 的值是 jQuery 选择器。 如果你指定了 tagName,那么,生成的 View 以该 TagName 为最顶上节点标签。 如果你指定了 className,那么 tagName 的 className 为你指定的 class。


谢邀,但backbone没怎么使用过,看起来是用来选择DOM的,应该是在定义view时使用的,tagName是标签名,比如div,a。el应该是一个DOM元素,而className是类名,就是class属性。


如果你指定了el,则该视图的根元素就是你所指定的el。el可以是jquery对象,也可以是jquery选择器,或者原生的Element对象。

如果你没有指定el,Backbone会为你自动生成这个视图的根元素,tagName是用于指定这个跟元素的标签类型的,如果tagName: 'div'tagName: 'li'。className用于指定这个根元素的类名。

具体你可以看以下backbone的源码片段:

var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    options || (options = {});
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
};

// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
    if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
        this.setElement($el, false);
    } else {
        this.setElement(_.result(this, 'el'), false);
    }
}

// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
    if (this.$el) this.undelegateEvents();
    this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
    this.el = this.$el[0];
    if (delegate !== false) this.delegateEvents();
    return this;
},

willerce 讲的很详细了, backbone 有个默认的属性 tagName, 默认为空的 Div, 在没有指定 tagName 时,Backbone 会通过默认的 tagName 产生一个 jQuery 对象,即视图的 $el

【热门文章】
【热门文章】