Using jquery on Marionette itemView to addClass to this.$el

孤街醉人 提交于 2019-12-13 02:12:27

问题


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.


回答1:


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.

Check out slightly modified code on jsfiddle

And code itsself:

html:

<div id="conatainer"> </div>

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});

Output:

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">


来源:https://stackoverflow.com/questions/24097352/using-jquery-on-marionette-itemview-to-addclass-to-this-el

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!