2013-04-29 52 views
0

在我的骨幹,我做了一個onclick事件到每個模型,以更新名稱..工作正常。還我收到觸發在我看來,以更新模型的觀點..onclick事件更新模型屬性,但視圖不呈現

但視圖不更新模型..而不是在所有的HTML更改文本..

我的模型圖:

var studentView = Backbone.View.extend({ 
    tagName:'li', 
    events:{ 
     'click':"called" 
    }, 
    template:_.template($("#studentTemplate").html()), 
    render:function(){ 
     this.$el.append(this.template(this.model.toJSON())); 
     this.model.get('scored') > 60 ? this.$el.addClass("active") : null; 
     return this; 
    }, 
    called:function(){ 
     this.model.set('name','text'); // i am setting a name as 'text' for example 
    } 
}); 

我的渲​​染視圖:

var studentsView = Backbone.View.extend({ 
el:$(".page"), 
events:{ 
    "click #highScoreBtn":"showHighScore" 
}, 
initialize:function(){ 
    this.collection = new collection(student); 
    this.render(); 
    this.collection.on('change', this.renderOne,this); 
}, 
render:function(){ 
    var that = this; 
    _.each(this.collection.models, function(item){ 
     that.$el.find('ul').append(new studentView({model:item}).render().el); 
    }) 

}, 
renderOne:function(data){ 
    this.$el.find('ul').append(new studentView({model:data}).render().el); // appending as new element instead updating the existing one.. 
} 

})

那麼,什麼是錯的我的代碼..或任何一個糾正我這在我的jsfiddle ..提前

here is my jsfiddle link

謝謝..

+0

當你點擊一個studentView li,你是否期待學生的姓名改爲「文字」?我是否正確地閱讀您的問題? – kinakuta 2013-04-29 07:19:26

+0

是的,你是對的。 – 3gwebtrain 2013-04-29 07:25:13

+0

當模型的屬性發生變化時,Backbone不更新UI。您需要添加代碼來跟蹤「change」事件並再次呈現UI,或使用如下框架:http://rivetsjs.com/ – WiredPrairie 2013-04-29 10:45:31

回答

1

這是我的作品:

var studentView = Backbone.View.extend({ 
    tagName:'li', 
    events:{ 
     'click':"called" 
    }, 
    template:_.template($("#studentTemplate").html()), 
    initialize:function(){ 
     this.listenTo(this.model, 'change', this.render); 
    }, 
    render:function(){ 
     this.$el.html(this.template(this.model.toJSON())); 
     this.model.get('scored') > 60 ? this.$el.addClass("active") : null; 
     return this; 
    }, 
    called:function(){ 
     this.model.set('name','text'); 
    } 
});