我正在尝试使用 Backbonejs 阅读几个文档。它是一个 MVC 客户端框架。在 View 中我们编译一个模板并 渲染它们(将它们附加到 DOM,或进行一些操作)。 Backbone 有 underscore js 的依赖,它是模板的东西。
使用 Bbone,当操作 View 时,el
就会出现。我的
对 el
的理解是它引用了 DOM 对象
。如果不
dom 对象被分配给它,它假设一个空 div。
var Choose_view = new SearchView({ el: $("#choose_me") });
所以在上面的例子中,id为choose_me的div将会被操作, 当调用 choice_view 时。到目前为止一切顺利,但是有哪些 下面发生的事情按时间顺序排列,我无法得到,也是 如有任何冗余,请阅读查询的评论:
// the div with id search_container will be picked up by el
<div id="search_container"></div>
<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
//1. Compile the template using underscore, QUESTION: **what does this mean**?
var template = _.template( $("#search_template").html(), {} );
//2. Load the compiled HTML into the Backbone "el"
this.el.html( template );
}
});
// QUESTION: **When in 2. we have already mentioned, el, can we not over there
provide the div element?**
var search_view = new SearchView({ el: $("#search_container") });
</script>
<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
最佳答案
问题1
编译模板意味着您获得一个模板函数,您可以将数据对象作为模板函数的参数传递。这样,您就可以使用不同的数据对象多次评估模板函数,而只需编译一次。
compiledTemplate = _.template( $("#search_template").html());
this.el.html(compiledTemplate(data));
another.el.html(compiledTemplate(otherData));
在上面的示例中,您编译模板一次,然后使用两次。 在您提供的代码中,您同时编译并使用您的模板
所以
_.template( $("#search_template").html()); // Create a template function, the result is a function that you can call with a data object as argument
_.template( $("#search_template").html(), data); // Create a template function and call it directly with the data object provided, the result is a string containing html
引用号:http://underscorejs.org/#template
问题2
您可以直接提供 div 元素,但 el 是一个帮助器,用于检索将在其上委托(delegate)所有 DOM 事件的 View 的根元素。
如主干文档中所示
If you'd like to create a view that references an element already in the DOM, pass in the element as an option:
new View({el: existingElement})
关于javascript - 在backbonejs中编译模板是什么意思以及更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12839802/