以下backbone.js示例中的模型,控制器和视图是什么?

时间:2012-01-06 11:09:18

标签: javascript model-view-controller backbone.js

我收到了这段代码:

(function($){
  var ListView = Backbone.View.extend({
    el: $('body'), // el attaches to existing element

events: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.

    events: {
      'click button#add': 'addItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here

      this.counter = 0; // total number of items added thus far
      this.render();
    },

render() now introduces a button to add a new list item.

    render: function(){
      $(this.el).append("<button id='add'>Add list item</button>");
      $(this.el).append("<ul></ul>");
    },

addItem(): Custom function called via click event above.

    addItem: function(){
      this.counter++;
      $('ul', this.el).append("<li>hello world"+this.counter+"</li>");
    }
  });

  var listView = new ListView();      
})(jQuery);

来自this教程。

据我所知,Backbone.js在前端引入了MVC模式。 但是在上面的代码中我无法看到。

任何人都可以向我解释一下吗?

3 个答案:

答案 0 :(得分:2)

在backbone.js中技术上没有控制器。主要结构是模型,视图,集合(充当数组并包含许多模型)和路由器。

您列出的链接 - http://arturadib.com/hello-backbonejs/ - 可能是学习Backbone.js的最佳方式 - 尤其是在Javascript中没什么背景知识。所以你走在正确的轨道上。该项目是backbone.js待办事项列表教程的直接导入:http://documentcloud.github.com/backbone/docs/todos.html

该网站还将在更基本的层面上解释事情 - 我发现它非常有用:http://backbonetutorials.com/

答案 1 :(得分:1)

这只是视图部分代码。请参阅同一教程中的其他.js文件。更好地检查从1.js到5.js的所有文件 最好先检查一下:Hello Backbone

答案 2 :(得分:1)

请注意,Backbone View不是您在MVC中所期望的那个,它更像是MVP中的控制器或演示者。这是一个很好的article来描述这种差异。

相关问题