[英]How do I use fetched backbone collection data in another view?
嘗試學習Backbone並嘗試獲取數據時遇到絆腳石,我使用SearchBarView
視圖很好地獲取了數據,但是一旦獲取了數據,我不知道如何才能在SearchResultsView中獲取該數據以進行模板制作列出每個結果?
抱歉,如果這聽起來有點含糊,目前正在努力使我對此有所幫助,可以通過指導來解決!
SearchBarView
performSearch: function(searchTerm) {
// So trim any whitespace to make sure the word being used in the search is totally correct
var search = $.trim(searchTerm);
// Quick check if the search is empty then do nothing
if(search.length <= 0) {
return false;
}
// Make the fetch using our search term
dataStore.videos.getVideos(searchTerm);
},
轉到VideoSearchCollection
getVideos: function(searchTerm) {
console.log('Videos:getVideos', searchTerm);
// Update the search term property which will then be updated when the url method is run
// Note make sure any url changes are made BEFORE calling fetch
this.searchTerm = searchTerm;
this.fetch();
},
SearchResultsView
initialize: function() {
// listens to a change in the collection by the sync event and calls the render method
this.listenTo(this.collection, 'sync', this.render);
console.log('This collection should look like this: ', this.collection);
},
render: function() {
var self = this,
gridFragment = this.createItems();
this.$el.html(gridFragment);
return this;
},
createItems: function() {
var self = this,
gridFragment = document.createDocumentFragment();
this.collection.each(function (video) {
var searchResultView = new SearchResultView({
'model': video
});
gridFragment.appendChild(searchResultView.el);
}, this);
return gridFragment;
}
現在,我不確定如何在SearchResultView
獲取此數據,我想我需要從某個地方觸發一個事件並在initialize
函數中偵聽該事件,但是我不確定該在哪里觸發或是否在觸發自動制作。
目前尚不清楚100%如何初始化SearchResultView。
但是,為了擁有對集合的引用,您不能簡單地將引用傳遞給視圖的構造函數。 像這樣:
//在您的SearchbarView中
var myCollection = new Backbone.Collection(); // and you are populating the collection somewhere somehow
var searchResultView = new SearchResultView(myCollection) // you just pass this collection as argument.
myCollection.bind("change", function(){
searchResultView.parentCollection = myCollection;
}
在searchResultView內部,您只需例如通過parentCollection引用此集合。
如果您通過這兩個視圖的連接或關聯方式更加明確,則我可能會為您提供更多幫助。 但是,根據給定的信息,這似乎是最簡單的方法。
解決方案1
如果dataStore
是全局變量,則SearchBarView
dataStore - appears like a global variable
videos - a collection attached to global variable
然后在
SearchResultsView
this.listenTo(dataStore.videos, 'sync', this.render);
解決方案2
如果dataStore
不是全局變量
getVideos: function(searchTerm) {
console.log('Videos:getVideos', searchTerm);
// Update the search term property which will then be updated when the url method is run
// Note make sure any url changes are made BEFORE calling fetch
this.searchTerm = searchTerm;
var coll=this; //this should refer to the collection itself
this.fetch().done(function(){
var searchResultView = new SearchResultsView({collection:coll});
searchResultView.render();
});
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.