在Marionette itemView上使用jquery将class添加到this.$ el [英] Using jquery on Marionette itemView to addClass to this.$el
问题描述
当模型进行如下更改时,我试图将一个类添加到itemView的封闭标签中
I'm trying to add a class to the enclosing tag of an itemView when a model is changed as follows
View.Option = Marionette.ItemView.extend({
tagName: "li",
className: "option-item clearfix",
template: optionsItemTpl,
modelEvents: {
"change": "modelChanged"
},
modelChanged: function() {
console.log(this.$el);
this.$el.addClass('success');
}
});
以下输出我正在尝试将类添加到的元素
The follow outputs the element I'm trying to add the class to
console.log(this.$el);
但是没有添加该类,我只是看不出为什么会这样.
but the class isn't added and I just can't see why this would be.
推荐答案
我将您的代码复制到jsfiddle.好像它正在按预期工作. console.log(this.$ el)最初不会真正向您显示该值已更改,因为它输出了[li.option-item],但是您可以看到它也不显示其clearfix.如果深入研究$ el对象,您将看到成功类实际上已附加.您也可以通过回显this.el来验证这一点,它是不带jQUery包装器的纯DOM元素.
I copied your code to jsfiddle. Seems like it is working as intended. console.log(this.$el) will not actually show you that at first that value has changed as it outputs [li.option-item] but as you can see it does not show its clearfix neither. If you dig in deeper into the $el object you will see that success class is actually appended. You can also verify this by echoing this.el which is pure DOM element without jQUery wrapper.
并自行编码:
html:
<div id="conatainer"> </div>
javascript:
javascript:
var View = {};
View.Option = Marionette.ItemView.extend({
tagName: "li",
className: "option-item clearfix",
modelEvents: {
"change": "modelChanged"
},
modelChanged: function() {
console.log("Model Changed..");
this.$el.addClass('success');
$("#conatainer").append(this.$el);
console.log("Updated Views $el:")
console.log(this.$el);
console.log("Updated Views el:")
console.log(this.el);
}
});
var model = Backbone.Model.extend();
var model_instance = new model({test: 1});
console.log("Model Instance:");
console.log(model_instance)
var view = new View.Option({model: model_instance});
console.log("View: ")
console.log(view);
model_instance.set({test: 2});
输出:
Model Instance:
Object {cid="c1", attributes=Object, _changing=false, ...}
View:
Object {options=Object, cid="view2", model=Object, ...}
Model Changed..
Updated Views $el:
[li.option-item]
Updated Views el:
<li class="option-item clearfix success">
这篇关于在Marionette itemView上使用jquery将class添加到this.$ el的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!