简体   繁体   中英

What's the model, controller, view in the following backbone.js example?

I got this code:

(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);

from this tutorial.

I understand that Backbone.js introduces a MVC pattern to the front end. But in the code above I can't see that.

Can anyone explain that to me?

There is technically no controller in backbone.js. The main structures are Models, Views, Collections (that act as arrays and contain lots of models), and Routers.

The link you listed - http://arturadib.com/hello-backbonejs/ - is probably the best way to learn Backbone.js - especially with little background in Javascript. So you are on the right track. That project is a direct lead-in to the backbone.js ToDo list tutorial: http://documentcloud.github.com/backbone/docs/todos.html

This site will also explain things at a more basic level - I found it very helpful: http://backbonetutorials.com/

That's just the view part code. See other .js files in the same tutorial. Better check out all the files from 1.js to 5.js Better check it from first: Hello Backbone

Note that Backbone View isn't the one you expected in MVC its more like a controller or the presenter in MVP. Here is a nice article that describes this differences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM