2012-04-13 4 views
0

모델의 오브젝트와 관련된 View의 요소에 어떻게 액세스합니까?Backbone.js에서 모델의보기로 액세스

예를 들어 Products의 콜렉션이 있습니다. 각 제품에는 color 속성이 있습니다. color"red" 인 모든 제품을 '숨기기'(보기 표현을 삭제)하고 싶습니다.

내가 아는 유일한 방법은 모델의 개체 (아래 코드) destroy() 메서드를 호출하는 것입니다. 하지만 저는 Model의 객체를 파괴하고 싶지 않습니다. 모델을 변경하지 않고 View의 요소를 제거 할 수 있습니까?

// App 
hide_red_products: function() { 
    Product.each(function(x) { 
    if (x.attributes.color == "red") { x.destroy() } 
    }) 
} 


// Products' view 
initialize: function() { 
    this.model.bind('destroy', this.remove_element, this); 
} 

remove_element: function() { 
    return $(this.el).remove(); 
} 

답변

2

모델이보기의 작업을 제어해서는 안됩니다.

trigger 메서드를 사용하여 이벤트를 트리거해야합니다. 색상이 빨간색에서 빨간색으로 변경되었다고 가정하면 change 이벤트를 사용해야합니다. 변경 이벤트를 듣는 경우 hide_red_products 메소드가 필요하지 않습니다.

// App 
hide_red_products: function() { 
    Product.each(function(x) { 

    //if (x.attributes.color == "red") { x.trigger() } 
    // you should never access a models attributes using the attributes key 
    if (x.get('color') === 'red') { x.trigger('change'); } // shouldn't actually need this. 
    }) 
} 


// Products' view 
initialize: function() { 
    //this.model.bind('destroy', this.remove_element, this); 
    this.model.bind('change', this.remove_element, this); 
} 

remove_element: function(model) { 
    if (model.get('color') === 'red') { 
    $(this.el).remove(); 
    } 
} 

앞서 말한 것처럼 뷰가 이벤트를 수신 대기하는 경우 요소를 제거하는 메소드를 호출하지 않아도됩니다. 필요하다고 판단되면 change 또는 맞춤 이벤트를 사용하여 직접 실행할 수 있습니다. x.trigger('changedToRed');

+2

몇 분이면 나를 이길 수 있습니다. 나는 당신이 그것을 원한다면 quick'n'dirty (그리고 고안 한) 데모를 채웠다 : http://jsfiddle.net/ambiguous/Ex8KJ/1/ –

+0

매우 유용한 답변과 데모 애플 리케이션을 위해 고맙습니다! – evfwcqcg

관련 문제