如何从模型通知视图以更改主干中的值

时间:2013-07-19 07:16:18

标签: javascript jquery html css backbone.js

我有一个模型如:

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

观点:

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
        },

    });

如何从模型中获取信息并将其发送到视图以更改.css文件中的某些值?我知道方法,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您希望视图侦听模型上的更改。请参阅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'})
            }
        }
    });