Using jquery on Marionette itemView to addClass to

2019-08-08 08:39发布

问题:

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