Model, View PHP를 통해 json 데이터 가져와 model에 담고 view로 출력한다.

js API/backbonejs 2015. 6. 19. 13:49

# Model 만들기

==========================================

Taa = Backbone.Model.extend({

    urlRoot : '/list.php', // ajax를 통해서 json데이터를 가져올 php경로

    initialize: function(options){

        this.todate = options.todate;

        console.log(this.todate);

    },

    fetchParams: function(){

// model data에 값 등록

        this.fetch({ data: $.param({ todate: this.todate }) });


// urlRoot에 추가  query string 추가

        this.urlRoot+="?"+$.param({ todate: this.todate });  

    },

    url: function()

    {

        console.log(this.urlRoot);

        return this.urlRoot;

    }

});


# View

==========================================

TaaView = Backbone.View.extend({

    initialize: function(){

        _.bindAll(this, "render");

        this.model.fetch({

            success: this.render

        });

    },

    render: function(){

/*

{

"result":"true", 

"msg":[

{

position_day:20, 

list:[

{title:"제목"}

]

},


{

position_day:23, 

list:[

{title:"제목"}

]

}

]

}

*/

        console.log(JSON.stringify(this.model));


// 배열을 돌리면서 원하는 곳에 하기

        _.each(this.model.get('msg'), function(data){

            var dday_id = 'd'+data.position_day;

            var lists = data.list;


// unsderscore template 를 사용해 출력(난 jquery를 활용해 이미 불러온 템플릿 리소스 체크

            $('#'+dday_id).append($.template('calendar_data_template', {row : lists}));

        });

    }

});


# model 실행 --------------------------

var taa = new Taa({'todate' : '2015-05-01'});

taa.fetchParams();

        

# view 실행 ---------------------------

new TaaView({ model: taa });