在Backbonejs视图的render()方法中应用jQuery styiling
我有一个简单的对象层次结构(主干),例如:在Backbonejs视图的render()方法中应用jQuery styiling,jquery,backbone.js,Jquery,Backbone.js,我有一个简单的对象层次结构(主干),例如: var PersonView = Backbone.View.extend({ //child class tagName: 'li', template: _.template( $("#personTemplate").html() ), // RETURNS A FUNCTION!!! render: function(){ this.$el.html( this.template( this.mode
var PersonView = Backbone.View.extend({ //child class
tagName: 'li',
template: _.template( $("#personTemplate").html() ), // RETURNS A FUNCTION!!!
render: function(){
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
});
var PeopleView = Backbone.View.extend({ //container class
tagName: 'ul',
render: function(){
this.collection.each( function( person ){
var personVar = new PersonView( {model : person} );
this.$el.append( personVar.render().el );
}, this);
return this;
}
});
这只是一个例子。假设我想用jQuery为每个
元素(表示一个人)应用红色。这个方法(例如:$('li').css('color','red')
)必须在PersonView中的某个地方调用,因此当我在PeopleView中实例化它时,元素已经应用了该样式(通过jQuery)
同样,我想知道这是否可以通过jQuery(特别是在子类-PersonView中调用的方法)实现,而不是通过CSS实现。主干视图总是引用它们关联的DOM元素: 所有视图在任何时候都有一个DOM元素(el属性),不管它们是否已经插入到页面中。以这种方式,可以随时渲染视图[…] 作为扩展,
View.$el
始终指向正确的jQuery元素,因此您可以在PersonView渲染中应用任何jQuery函数:
var PersonView = Backbone.View.extend({
tagName: 'li',
template: _.template( $("#personTemplate").html() ),
render: function(){
this.$el.html( this.template( this.model.toJSON() ) );
this.$el.css('color', 'red');
return this;
}
});
请看这把小提琴的演示