javascript - backbone 视图里面的tagName的作用
巴扎黑
巴扎黑 2017-04-10 12:47:54
[JavaScript讨论组]

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

巴扎黑
巴扎黑

全部回复(4)
高洛峰

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

伊谢尔伦

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

PHP中文网

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

天蓬老师

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

如果你没有指定el,Backbone会为你自动生成这个视图的根元素,tagName是用于指定这个跟元素的标签类型的,如果tagName: 'p'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;
},
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号