將井字遊戲中的分數紀錄用rest api來實作
1.首先在routes.js中增加以下幾個設定
// partjs boilerplate
app.get('/timeline*', require('./views/timeline/index').init);
app.get('/post*', require('./views/post/index').init);
app.get('/unsplash*', require('./views/unsplash/index').init);
app.get('/about', require('./views/index').about);
app.get('/sensor', require('./views/index').sensor);
app.get('/dashboard', require('./views/index').dashboard);
app.get('/1/game', require('./views/api/game.js/index').read);
app.post('/1/game', require('./views/api/game.js/index').write);
app.post('/1/game:name', require('./views/api/game.js/index').test);
2.在上述的路徑中增加一個index.js的檔案內容如下
var score = {
you:0,
me:0
};
exports.read = function(req, res){
res.json(score);
};
exports.write = function(req, res){
var action = req.query;
var score = req.body; //===>body?什麼的函式庫來的
res.json(score);
};
exports.test = function(req, res){
var name = req.params.name;
console.log('name : '+ name);
res.json(score);
};
3.在Front end讀取rest api 使用backbone 框架
在game.js中設定model
app.Contact = Backbone.Model.extend({ //1
url: '/1/game',
defaults: {
you:0,
me:0
}
});
在view中加入變數的處裡函數
if(this.result.indexOf(3) !== -1){
var you = this.model.get('you');
this.model.set('you',you+1);
this.model.save();
alert('X 贏 ');
this.render();
}
if(this.result.indexOf(-3) !== -1){
var me = this.model.get('me');
this.model.set('me',me+1);
this.model.save();
alert('O 贏');
this.render();
}
4.接下來增加顯示的部分
render: function() {
this.$el.prepend(this.template( this.model.attributes ));//3
console.log(this.model.attributes)
var self = this;
setInterval(function(){
var item = Math.floor(Math.random()*9);
var me = $("[data-num="+ item +"]");
me.removeClass('fa-circle-o');
me.removeClass('fa-times');
self.n[item]=0;
},1000);
},
沒有留言:
張貼留言