1

我有一个具有这些功能的视图 -

  initialize:=>
    @populateSearchHistory()
    @el

  populateSearchHistory:=>
    console.log(pastSearches)
    @$el.find("#searchHistoryContainer").append(Handlebars.templates["$$ uri $$-searchHistory"]())
    @collection.add(stuff)


  @collection.on "add", (toAdd)->
    console.log(toAdd)

但是没有记录“添加”。到底是怎么回事?

更新-

我尝试在初始化函数中这样做 -

initialize:=>
  @collection.on "add", @populateSearchHistory

populateSearchHistory 现在在哪里

populateSearchHistory:(toAdd)=>
  console.log(toAdd)

但是, toAdd 是一个空模型,我需要它具有我添加的值。

更新编译的javascript

var _this = this;

({
  initialize: function() {
    _this.populateSearchHistory();
    return _this.el;
  },
  populateSearchHistory: function() {
    console.log(pastSearches);
    _this.$el.find("#searchHistoryContainer").append(Handlebars.templates["$$ uri $$-searchHistory"]());
    return _this.collection.add(stuff);
  }
});

this.collection.on("add", function(toAdd) {
  return console.log(toAdd);
});

更新

好的 - 所以 init 函数中的绑定起作用了,传入的未初始化查询是因为我有一个 for 循环遍历集合并在集合中添加每个模型 - 每个模型都是未定义的 - 为什么会发生这种情况?

4

1 回答 1

0

这里jsfiddle(更新):http: //jsfiddle.net/85YxD/

SearchModel = Backbone.Model.extend();

SearchCollection = Backbone.Collection.extend({
    model : SearchModel
});

myCollection = new SearchCollection();

SearchView = Backbone.View.extend({

   initialize: function() {
       var _this = this;
        _this.populateSearchHistory();
   },

    populateSearchHistory: function() {
        var _this = this;
       // your code here
       var stuff = new SearchModel({
          key : 'value'          
       })

       //model can be added both way 
       console.log('model1 added.......');
       _this.options.list.add(stuff);

       //Or,  
       console.log('model2 added.......');
      _this.options.list.add({
          key1 : 'value1',
          key2 : 'value2'
       });

       //TODO : add loop for adding models here

       return _this;
   }

});

myCollection.on("add", function(toAdd) {
    console.log('added model', toAdd);
    console.log('updated collection', myCollection.toJSON());  
});


new SearchView({
   list : myCollection
});

​</p>

于 2012-09-12T06:01:53.467 回答