backbone.js的模板与el、render的关系


分三种情况:

第1种:不使用任何框架

第2种:使用Hogan框架

第3种:使用mustache框架

..

第N种:使用underscore的_.template

一、不使用任何框架

var tmpDiv = $('<div></div>').append(createFeedTpl);

var View = Backbone.View.extend({
    el:"<div></div>",
    events:{},
    initialize:function(){
        this.render();
    },
    render:function(){
        this.$el.empty();
        this.$el.html(tmpDiv.find('#createFeedTemplate').html());
    }
});

二、使用hogan框架

var tmpDiv = $('<div></div>').append(createFeedTpl);
var createFeedTemplate = Hogan.compile(tmpDiv.find('#createFeedTemplate').html());//将其预编译
tmpDiv.remove();
var View = Backbone.View.extend({
    el:"<div></div>",
    events:{},
    initialize:function(){
        this.render();
    },
    render:function(){
        this.$el.empty();
        this.$el.html(createFeedTemplate.render());//createFeedTemplate有render方法,并且可以传参render(data)
    }
});

二、使用mustache框架

var tpl = require('crownSheetTpl');
//载入模板
$.Mustache.addFromString(tpl);
var View = Backbone.View.extend({
    events:{},
    initialize:function(){
        this.$el.empty().mustache('crownSheet-crownSheetEditor-Template', this.model.toJSON());//载入模板
    },
    
});

对于第三种情况,根本没有明设el的值,那么el是什么呢?

根据官方文档:

All views have a DOM element at all times (the el property), whether they’ve already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible. this.el is created from the view’s tagName, className, id and attributes properties, if specified. If not, el is an empty div.

简单说,就是如果你没有设置,那么系统将给你默认哪一个空div


发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>