2013-03-27 71 views
0

我試圖創建兩個視圖並在不同情況下更改集合。我不知道如何設置this.collection.bind,因此它會在每次集合更改時引發事件呈現。主幹不發射呈現事件

有3種情況,我希望視圖BusinessListViewrender

  1. this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]);
  2. this.businesslist.set();這就要求this.collection = new Businesses([{ name: '3'}, { name: '4' }]);
  3. this.search_location = new SearchLocation();這是不同的看法,然後把收集來查看BusinessListView

我曾期待看到數據在控制檯上1和2,它不起作用。如果手動添加.render(),我可以看到集合已更改。你能解釋一下這是如何工作的嗎?

UPDATE

感謝Alex這是完全可行的解決方案:

http://jsfiddle.net/feronovak/RAPjM/

var App = { 
    run: function() { 
     this.businesslist = new BusinessListView(); 
     this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]); 
     // this.businesslist.render(); // uncomment to see collection change 
     this.businesslist.set(); 

     this.search_location = new SearchLocation(); 
    } 
}; 

Business = Backbone.Model.extend({}); 
Businesses = Backbone.Collection.extend({ 
    model: Business 
}); 

BusinessListView = Backbone.View.extend({ 
    initialize: function(options) { 
     this.collection = new Businesses(); 
     this.collection.bind("reset", this.render(), this); 
    }, 
    render: function() { 
     console.log(this.collection.toJSON()); 
    }, 
    set: function() 
    { 
     this.collection = new Businesses([{ name: '3'}, { name: '4' }]); 
     // this.render(); // uncomment to see collection change 
    } 
}); 

SearchLocation = Backbone.View.extend({ 
    el: "#search", 
    initialize: function() { 
     this.sendData(); 
    }, 
    sendData: function() { 
     // Send [{ name: '5'}, { name: '6' }] to this.businesslist = new Businesses([{ name: '5'}, { name: '6' }]); 
    } 
}); 

$(document).ready(function(e) { 
    App.run(); 
}); 
+0

不改變收集調用復位事件?我希望如果我手動更改集合(僅在此示例中),則會調用渲染。 – feronovak 2013-03-27 13:20:36

+0

刪除我最後的評論,因爲它是不正確的,我猜。你的jsfiddle顯示渲染方法正在運行。 – Loamhoof 2013-03-27 13:21:40

+0

通過創建一個新對象,偵聽器消失。所以你只是不聽新的。 – Loamhoof 2013-03-27 13:25:59

回答

1

你繼續設置this.collection參考不同的實例。它不會「重置」,因爲你永遠不會重置initialize中引用的對象。

代替:

set: function() 
    { 
     this.collection = new Businesses([{ name: '3'}, { name: '4' }]); 
    } 

嘗試:

set: function() 
    { 
     this.collection.reset([{ name: '3'}, { name: '4' }]); 
    } 

,並在運行中刪除:

this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]); 

例子這裏:http://jsfiddle.net/aXJ9x/1/

+0

它還沒有觸發this.render()。這行(this.businesslist.collection)是有意的,我想看看如何使用不同的方法來修改集合。你可以分叉jsfiddle來顯示工作的例子嗎? – feronovak 2013-03-27 13:29:05

+0

小提琴添加到帖子的底部 – 2013-03-27 13:40:35

+0

謝謝,很好。我需要做什麼才能從SearchLocation視圖調用collection 5,6? – feronovak 2013-03-27 13:48:08