我有一个模型,例如:
var resultEntityModel = Backbone.RelationalModel.extend({
defaults : {
name : "",
bgOccurence : "",
fgOccurence : "",
bgOccurenceCount : "",
fgOccurenceCount : "",
},
initialize : function() {
var bgOccurence = this.set("bgOccurence", bgOccurence);
var fgOccurence = this.set("fgOccurence", fgOccurence);
if((Math.abs((bgOccurence-fgOccurence))) >= 10){
// send information to view that background should be red
}else{
// send information to view that background should be white
}
},
});
还有一个 View :
var resultEntityView = Marionette.CompositeView.extend({
tagName : "tr",
template : ResultEntityPanel,
initialize: function () {
this.model.on(...) // it should take information from model
//and change css values according to this information
},
});
我如何从模型中获取信息并将其发送到 View 以更改 .css 文件中的某些值?我知道方法,但我不知道怎么做。
最佳答案
您希望 View 监听模型的变化。参见 Backbone listenTo .
未经测试的代码,但应该这样做:
型号:
var resultEntityModel = Backbone.RelationalModel.extend({
defaults : {
name : "",
bgOccurence : "",
fgOccurence : "",
bgOccurenceCount : "",
fgOccurenceCount : "",
},
initialize : function() {
this.set("bgOccurence", bgOccurence);
this.set("fgOccurence", fgOccurence);
}
});
查看:
var resultEntityView = Marionette.CompositeView.extend({
tagName : "tr",
template : ResultEntityPanel,
initialize: function () {
this.listenTo(this.model, "change:bgOccurence", this.setBg);
this.listenTo(this.model, "change:fgOccurence", this.setBg);
},
setBg: function(model, value) {
var bgOccurence = model.get('bgOccurence'),
fgOccurence = model.get('fgOccurence');
if ((Math.abs((bgOccurence-fgOccurence))) >= 10) {
$('body').css({'background-color':'red'})
} else {
$('body').css({'background-color':'white'})
}
}
});
关于javascript - 如何通知模型中的 View 以更改主干中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17740179/