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

作者:zccst

分三种情况:
第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




如果您觉得本文的内容对您的学习有所帮助,您可以微信:
backbone.js的模板与el、render的关系

你可能感兴趣的:(JavaScript,backbonejs)