まずはデータ定義部分となるModelから紹介します。
Backbone.Modelは、下記の役割を担当します。
MemoというModelを定義してみます。バックエンドサーバーとして、Kii Cloudのユーザースコープを使ってみます。
var BASE_URL = 'https://api-jp.kii.com/api';
var Memo = Backbone.Model.extend({
urlRoot : BASE_URL + '/apps/<appID>/users/me/buckets/memo/objects',
idAttribute: "_id",
create : function(title, contents, callback) {
var _this = this;
this.save({
"title" : title,
"contents" : contents
}, {
headers : context.createHeader('application/json', true),
success : function() {
callback.success();
}
});
},
del : function(callback) {
var c = this;
this.destroy({
headers : context.createHeader(null, true),
success : function() {
callback.success();
}
});
}
});
urlRootで、サーバーのどのURLに対応するのかを指定します。このURLは、次のように使われます。
idAttributeは、サーバーのオブジェクトIDがJSONのどのフィールドに対応するのかを指定します。Kii Cloudの場合、オブジェクトのIDは_idに入っているので、"_id"を指定しています。
contextも同様に定義してみます。ログイン時に使います。
var Context = Backbone.Model.extend({
url : BASE_URL + '/oauth2/token',
createHeader : function(contentType, hasAuth) {
var headers = {
'x-kii-appid' : '<app id>',
'x-kii-appkey' : '<app key>',
};
if (contentType != null) {
headers['content-type'] = contentType;
}
if (hasAuth) {
headers.authorization = 'bearer ' + this.get('access_token');
}
return headers;
},
isLoggedIn : function() {
var token = this.get('access_token');
return token != null && token.length > 0;
},
login : function(username, password, success, failed) {
var c = this;
this.save({
'username' : username,
'password' : password
}, {
headers : this.createHeader('application/json', false),
success : function() {
success(c);
},
error : function() {
failed();
}
});
}
});
newでオブジェクトを作って、create()を呼ぶと、サーバーに新規作成リクエストを投げます。
var context = new Context();
context.login('<username>', '<password>', function() {
var memo = new Memo();
memo.create('newMemo', 'secret diary', {
success : function() {
console.log('created!');
}
});
}, function() {
console.log('login failed');
});