2012-07-21 4 views
0

다음과 같은 쉬운 예입니다.백본보기에서 다른 것을 선택 해제하는 방법?

매번 아바타가 많으며 선택할 수있는 아바타는 하나뿐입니다.

'Avatar'모델, 'Avatars'컬렉션 및 모델보기 'AvatarView'가 있습니다. 또한 'AvatarAppView'라는보기가 있으며 앱보기를 렌더링합니다.

내 구현은 다음과 같습니다 :

한 아바타를 선택

, 이벤트, 모델의 뷰 'AvatarView'에 따라 트리거되어 다음을 선택합니다 클릭하지만 다른 모델이 선택되지 않은 수 없습니다.

좋은 해결책이 있습니까? 고맙습니다.

답변

0

백본보기는 Backbone.Events이 혼합되어 있으므로보기가 자체 이벤트를 생성 할 수 있고 다른보기는 해당 이벤트를 수신 할 수 있습니다.

select: function() { 
    // Mark this avatar as selected... 
    this.trigger('selected', this); 
}, 
unselect: function() { 
    // Undo the "mark this avatar as selected" from above. 
} 

을 다음 AvatarAppView 그 이벤트를 수신 할 수 있습니다 :이 선택 될 때 그래서 AvatarView 이벤트를 트리거 할 수 있습니다

initialize: function() { 
    _.bindAll(this, 'selected'); 
    //... 
}, 
render: function() { 
    this.kids = [ ]; 
    this.collection.each(function(m) { 
     var v = new AvatarView({ model: m }); 
     v.on('selected', this.selected); 
     this.kids.push(v); 
     this.$el.append(v.render().el); 
    }, this); 
    return this; 
} 

그런 AvatarAppView에 대한 간단한 selected 이벤트 핸들러는 다른 AvatarView의 선택을 취소합니다 :

selected: function(v) { 
    _.chain(this.kids).reject(function(k) { return k == v }).invoke('unselect'); 
} 

데모 : http://jsfiddle.net/ambiguous/thRHK/

+0

정말 대단해! 나에게 많이 가르쳐 줘, 고마워. – goofansu

+0

나는 avatarView와 avatarAppView를 두개의 파일로 나눴고, this.trigger ('selected', this); avatarAppView에서 'selected'이벤트를 트리거 할 수 없습니다. – goofansu

+0

@goofansu :하지만 같은 파일에있을 때 효과가 있었습니까? 이벤트가 트리거되면 어떻게됩니까? –

관련 문제