2012-03-31 9 views
10

Zasadniczo co potrzebne jest, aby zrobić coś takiegoJak mogę dynamicznie ustawić nazwę klasy dla widoku Backbone.js na podstawie jego atrybutów modelu?

App.CommentView = Backbone.View.extend({ 
    className: function() { 
    if (this.model.get('parent_id')) { 
     return 'comment comment-reply'; 
    } else { 
    return 'comment'; 
    } 
    }, 

Problem polega na tym, że w funkcji przekazany do className jest wykonywany w kontekście html szablonu widoku, więc nie mogę nazwać this.model.

Czy jest jakiś sposób uzyskania dostępu do modelu w tym momencie procesu renderowania? Czy muszę ustawić klasę później, na przykład w funkcji render?

Odpowiedz

14

To brzmi jak zadanie dla modelu wiążące.

App.CommentView = Backbone.View.extend({ 
    initialize: function() { 
     // anytime the model's name attribute changes 
     this.listenTo(this.model, 'change:name', function (name) { 
      if (name === 'hi') { 
      this.$el.addClass('hi'); 
      } else if...... 
     }); 
    }, 
    render: function() { 
     // do initial dynamic class set here 
    } 
2

Byłoby znacznie łatwiejsze myślę, aby użyć this.$el.toggleClass lub po prostu dodać klasę wewnątrz render.

Jednak jeśli chcesz ustawić klasę przy konstruowaniu pogląd, można przekazać go jako opcja:

view = new App.CommentView({ 
    model: model, 
    className: model.get('parent_id') ? 'comment comment-reply' : 'comment' 
}) 
3

Należy użyć atrybutów hash/funkcja:

attributes: function() { 
//GET CLASS NAME FROM MODEL 
return { 'class' : this.getClass() } 
}, 
getClass: function() { 
    return this.model.get('classname') 
} 
+0

Nie, to nieprawda. Ta funkcja "attributes" jest sprawdzona w metodzie _ensureElement() iw tym momencie nie masz dostępu do this.model –

Powiązane problemy