2011-09-14 76 views
1

我正在关注位于here的BackboneJs上的教程。BackboneJs教程问题

关于在render方法,他做了以下中途下:

events: { 'click button#add': 'addItem' }, 

    initialize: function() { 
     this.collection = new List(); 

     // Collection event binder 
     this.collection.bind('add', this.appendItem); 

     this.counter = 0; 
     this.render(); 
    }, 

    render: function() { 
     this.el.append("<button id='add'> Add List Item</button>"); 
     this.el.append("<ul></ul>"); 

     _(this.collection.models).each(function(item){ 
      // in case collection is not empty 
      appendItem(item); 
     }, this); 
    }, 

    addItem: function() { 
     var item = new Item(); 

     this.counter++; 

     item.set({ 
      part2: item.get('part2') + " " + this.counter 
     }); 

     this.collection.add(item); 
    }, 

    appendItem: function (item) { 
     $('ul').append('<li>' + item.get('part1') + " " + item.get('part2') + '</li>'); 
    } 

我有几个关于线下的问题。

_(this.collection.models).each(function(item){ 
    // in case collection is not empty 
    appendItem(item); 
}, this); 

下划线_在这方面做了什么?

为什么这甚至需要?

如果收集不是空的,则说明注释。但是,没有这条线它工作得很好。 initialize函数中的bind覆盖告诉Backbone在集合上触发add事件时运行this.appendItem,或者我认为并通过删除相关行来确认。

回答

2

我认为这个方法通常将一个数组包装在一个“下划线”辅助类中,使它可以访问所有的underscore.js辅助方法。在这种情况下,.each方法来自下划线助手类。

就像你说的,但是,如果没有它,这应该可以正常工作。这可能是本教程编写的骨干版本(v0.3.3)需要_方法来迭代像这样的模型数组。

underscore.js文档(http://documentcloud.github.com/underscore/)讨论了使用_()作为方法调用,而不是在面向对象的mannter中使用库。

+0

完美。谢谢。我完全忘记了下划线是一个依赖:)我认为这可能是一个主干的事情。 –