2014-06-07 62 views
1

我想,當一個模型改變爲一個類添加到ItemView控件的外圍標籤如下

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

後續輸出的元素我'試圖添加類到

console.log(this.$el); 

但類沒有添加,我只是不明白爲什麼會這樣。

回答

1

我將你的代碼複製到jsfiddle。似乎它按預期工作。 console.log(this。$ el)實際上並不會告訴你,起初這個值已經改變了,因爲它輸出了[li.option-item],但是你可以看到它並沒有顯示它的clearfix。如果您深入挖掘$ el對象,您會看到成功類實際上被追加了。您也可以通過echo this.el來驗證這是純粹的DOM元素沒有jquery包裝。

Check out slightly modified code on jsfiddle

和代碼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}); 

輸出:

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