backbone:如何将数据传递到渲染视图

时间:2015-02-11 08:07:02

标签: javascript backbone.js

有没有办法将数据传递给渲染

以下代码是我目前正在使用的代码:

    render:function() {
        var background = 
        var highlight = this.model.get('highlight');
        $(this.el).find('div').each(function(index,element) {
            if(index < highlight) {
                $(element).css({'background': 'url("assets/img/alphabet/ok/ok.png"), url('+background+')'});
                $(element).attr('id', 'ok');
            } else {
                $(element).removeAttr('id');
            }
        })
    }

也许就像这张照片:

enter image description here

1 个答案:

答案 0 :(得分:0)

......你可以这样做:

this.background : [],
//...
initialize : function(){
//...
    this.background.push(string.charAt(i));
//...
},
render : function(){
    //...
    var background = this.background[index];
    //...
}

但是,for内的initialize循环也可能留在render内,因为它会呈现视图(.append()}。

编辑注:

我再说一遍,可以在渲染函数的初始化函数中移动循环。

我尝试更改骨干视图结构:

var WordView = Backbone.View.extend({

    initialize : function(){
        this.listenTo(this.model,"remove",this.remove);
    },

    render : function(){
        var $Div,
            string = this.model.get('string'), //use _string (string can cause some issue in IE)
            highlight = this.model.get("highlight"),

            letter_width = 36,
            letter_heigth = 35,
            word_width = string.length * letter_width;

        if(this.model.get("x") + word_width > $(window).width()) this.model.set({x:$(window).width() - word_width});

        $(this.el).css({
            position:"absolute",
            top : this.model.get("y"),
            left : this.model.get("x")
        });

        var background,char;
        for(var i; i < string.length; i++){
            char = string.charAt(i);
            background = "url('"+char+"') no-repeat";
            $Div.removeAttr("id"); //seems useless

            if(i < highlight){
                background = "url('assets/img/alphabet/ok/ok.png'),url('"+char+"')";
                $Div.id("ok"); //maybe is better $Div.class("ok");
            }

            $Div = $("<div>").clone();
            $Div.css({
                width : letter_width,
                heigth : letter_height,
                float: "left",
                "background" : background
            }).appendTo($(this.el));

        }
    }
});