2012-05-09 3 views
0

컬렉션 안에 두 개의 서로 다른 모델이 있는데, 뷰 내부에서 어떻게 액세스합니까? 질문은 2 부분으로 구성되어 있습니다. 질문이 명확하지 않으면 알려주십시오.컬렉션에서 여러 유형의 모델에 액세스하는 방법은 무엇입니까?

1 부

모델 1

Movie = Backbone.Model.extend({ 
    initialize:function(){ 
     console.log("The model 'Movie' initialized"); 
    } 
}); 

모델 2

Songs = Backbone.Model.extend({ 
    initialize:function(){ 
      console.log("The model 'Songs' initialized"); 
    } 
}); 

var movie = new Movie({type:"movie",name:"Lord of the Rings",year:"2006"}); 
var songs = new Songs({type:"songs",name:"Rahna Thu", artist:"A R Rahman", album:"Delhi-6"}); 

var entertainment = new Backbone.Collection([movie,songs]); 
다음으로이 모델에 대해 생성 된 인스턴스는 배열로 컬렉션에 추가

0

내보기에서이 모델에 어떻게 액세스합니까? 이 모델을로드하고 템플릿에 바인딩하려면? 내가 올바른 생각하면 나도 몰라하지만 난 제대로 경고를 얻고 있지만 나는이

MainView = Backbone.View.extend({ 
    collection:entertainment, 
    initialize:function(){ 
     $.each(this.collection.toJSON(),function(i,item){ 
      if(item.type=="songs"){ 
       alert("Song: "+item.name+" Artist: "+item.artist+" Album: "+item.album); 
      } 
     }); 
    } 
}); 
var mainview = new MainView({el:$('body')}); 

같은 것을했다, 내가 그것을 할 수있는 올바른 방법인지 알 필요가있다.

2 부

이제 질문의 나의 두 번째 부분. 이 모델에 'urlRoot'가 있다면 어떨까요? 모델을 미리 가져 와서 컬렉션을 채우려면 어떻게해야합니까?

e.e.

Movie = Backbone.Model.extend({ 
    urlRoot:"https://localhost:8080/entertainment/movies" 
}); 

Songs = Backbone.Model.extend({ 
    urlRoot:"https://localhost:8080/entertainment/songs" 
}); 

를 다음과 같이 내 두 번째 시나리오에서 나의 모델은 지금, 어떻게 컬렉션에 이러한 모델을 추가하고 뷰 내부에 액세스합니까?

실제 솔루션은 대시 보드 페이지가로드 될 때 그리드, 차트 및 기타 서버 측 데이터와 같은 여러 데이터를로드하는 것입니다. 이 모든 것이 페이지로드에서 채워질 필요가 있으므로이 솔루션을 생각했습니다. 나는 여기서 옳은 일을하고 있는가? 아니면 더 좋은 방법이 있을까요?

죄송합니다. 문제는 상당히 길지만 실제로 여기에 대한 전문가의 조언을 부탁드립니다.

답변

0

백본은 실제로 모델과 컬렉션이 다른 방식으로 디자인되었습니다. 모델은 유사한 데이터 지향 객체에서 유사해야합니다. 컬렉션은 유사한 모델에 대한 집계가되어야합니다. 당신이 휴식하기 때문에 당신은 하나 개의 컬렉션 모델의 다른 유형을해서는 안 (또는 잘못된 만듭니다) 데이터베이스 API를

var Movie = Backbone.Model.extend({ 
    initialize: function() { console.log('movie initialized') }); 
}); 

var Song = Backbone.Model.extend({ 
    initialize: function() { console.log('song initialized') }); 
}); 

var Movies = Backbone.Collection.extend({ 
    model : Movie, 
    url : 'https://localhost:8080/entertainment/movies' 
    initialize: function() { console.log('movies collection initialized') }); 
}); 

var Songs = Backbone.Collection.extend({ 
    model : Song, 
    url : 'https://localhost:8080/entertainment/songs' 
    initialize: function() { console.log('songs collection initialized') }); 
}); 

MainView = Backbone.View.extend({ 
    initialize:function(){ 
     this.entertainment = { 
      songs : new Songs(), 
      movies : new Movies() 
     }; 
     this.entertainment.songs.each(function(model) { // Underscore method 
      alert("Song: "+model.get('name')+" Artist ..."); 
     }); 
    } 
}); 

:

앱 같은 것을 보일 것입니다.

관련 문제