龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

Javascript MVC框架Backbone.js详解(2)

时间:2014-09-22 15:03来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: var Document = Backbone.View.extend({ tagName: "li", className: "document", render: function() { // ... } }); template方法 视图的template属性用来指定网页模板。

复制代码 代码如下:

var Document = Backbone.View.extend({
  tagName: "li",
  className: "document",
  render: function() {
   // ...
  }
});

template方法

视图的template属性用来指定网页模板。

复制代码 代码如下:

var AppView = Backbone.View.extend({
      template: _.template("<h3>Hello <%= who %><h3>"),
});

上面代码中,underscore函数库的template函数,接受一个模板字符串作为参数,返回对应的模板函数。有了这个模板函数,只要提供具体的值,就能生成网页代码。
复制代码 代码如下:

var AppView = Backbone.View.extend({
      el: $('#container'),
      template: _.template("<h3>Hello <%= who %><h3>"),
      initialize: function(){
        this.render();
      },
      render: function(){
        this.$el.html(this.template({who: 'world!'}));
      }
});

上面代码的render就调用了template方法,从而生成具体的网页代码。

实际应用中,一般将模板放在script标签中,为了防止浏览器按照JavaScript代码解析,type属性设为text/template。

复制代码 代码如下:

<script type="text/template" data-name="templateName">
    <!-- template contents goes here -->
</script>

可以使用下面的代码编译模板。
复制代码 代码如下:

window.templates = {};
var $sources = $('script[type="text/template"]');
$sources.each(function(index, el) {
    var $el = $(el);
    templates[$el.data('name')] = _.template($el.html());
});

events属性

events属性用于指定视图的事件及其对应的处理函数。

复制代码 代码如下:

var Document = Backbone.View.extend({
  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  }
});

上面代码中一个指定了三个CSS选择器的单击事件,及其对应的三个处理函数。

listento方法

listento方法用于为特定事件指定回调函数。

复制代码 代码如下:

var Document = Backbone.View.extend({
  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  }
});

上面代码为model的change事件,指定了回调函数为render。

remove方法

remove方法用于移除一个视图。

复制代码 代码如下:

updateView: function() {
  view.remove();
  view.render();
};

子视图(subview)

在父视图中可以调用子视图。下面就是一种写法。

复制代码 代码如下:

render : function (){
    this.$el.html(this.template());
    this.child = new Child();
    this.child.appendTo($.('.container-placeholder').render();
}

Backbone.Router

Router是Backbone提供的路由对象,用来将用户请求的网址与后端的处理函数一一对应。

精彩图集

赞助商链接