Backbone学习笔记 - View篇

Backbone是一种Web端的MVC框架,这里纪录学习Model,View和Collection的笔记。

1 View

initialize构造函数

Backbone.View 与jQuery库紧密结合。

var SearchView = Backbone.View.extend({

  initialize:function(){ alert("Alerts suck.");

} });

var search_view = new SearchView();

initialize 就类似构造函数。

 

"el" 属性

"el" 属性关联 the DOM object. 每个Backbone的View都有一个 "el" 属性, 如果未指定,Backbone会创建一个空得el,指向一个空得div元素。

 

载入template

Backbone的这项功能依赖Underscore库。Underscore提供了一个函数集,算是jQuery功能的补充,函数集可以在这里查询:

http://underscorejs.org/

而Template是Underscore中提供的一个函数,其主要作用是将JS中可能遇到的HTML的代码剥离出来,以文件的形式加载。这样提高了JS代码的可控性,HTML代码也更容易编辑了。让我们看一个例子:

<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>

<div id="search_container"></div>

<script type="text/javascript">
  var SearchView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    render: function(){
      // Compile the template using underscore
      var template = _.template( $("#search_template").html(), {} );
      // Load the compiled HTML into the Backbone "el"
      this.$el.html( template );
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });
</script>
search_template中的界面布局部分会被template加载进来用于最后的显示。但如何将search_template的部分单独做为一个文件存放,还没弄明白。

添加事件
events: {
      "click input[type=button]": "doSearch"
    },
    doSearch: function( event ){
      // Button clicked, you can access the element that was clicked with event.currentTarget
      alert( "Search for " + $("#search_input").val() );
    }

添加变量

<label><%= search_label %></label> 这句是添加变量的写法。

<script type="text/template" id="search_template">
    <!-- Access template variables with <%= %> -->
    <label><%= search_label %></label>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
</script>

添加变量的功能可以动态指定界面中显示变量的值。

var SearchView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    render: function(){
      var variables = { search_label: "My Search" };
      var template = _.template( $("#search_template").html(), variables );
      this.$el.html( template );
    },
    events: {
      "click input[type=button]": "doSearch"
    },
    doSearch: function( event ){
      // Button clicked, you can access the element that was clicked with event.currentTarget
      alert( "Search for " + $("#search_input").val() );
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });

 

参考资料:

https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-view

 

 

posted @ 2015-12-09 15:21  Dawnli  阅读(320)  评论(0编辑  收藏  举报