视图渲染:是否有更好的方法来控制视图元素的类名?
var myView = Backbone.View.extend({
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
这是我想要的功能,但它不起作用。我不确定类名何时确定,但被调用者只是元素本身;在这种情况下,它将是 。有没有办法让 className 访问模型?
目前,我可以在模板中放置另一个 div,以便控制该类,但如果我能够从视图本身控制类名称,则绝对不需要该 div。
var myView = Backbone.View.extend({
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
That's the functionality I would like, but it doesn't work. I'm not sure when the class name is determined, but the callee is just the element itself; in this case, it would be <div></div>
. Is there a way to give className access to the model?
I can, and currently, put another div in my template, in order to control the class, but that div is definitely not needed if I am able to control the class name from the View itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果是我,我可能会在
render()
中使用辅助函数设置该类型的类:如果需要,您可以稍后在事件处理程序中重用
applyClass
到:If it were me, I'd probably set that type of class within
render()
use a helper function:You could then reuse
applyClass
in an event handler later if you need to:您需要在初始化方法中使用 _.bindAll 设置 className 函数的上下文
You need to set the context of the className function by using _.bindAll in the initialize method
或者,您可以避免
className
属性并使用attributes
函数...Alternatively, you could avoid
className
property and useattributes
function...