Last active
August 29, 2015 13:57
-
-
Save moskytw/9596864 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// class Profile | |
var Profile = function (obj) { | |
/* Model */ | |
this._model = {}; | |
/* View */ | |
this.$view = $(Profile.template); | |
this.$nick = this.$view.find('.nick'); | |
this.$error = this.$view.find('.error'); | |
/* Controller */ | |
var _this = this; | |
this.$view.on('click', 'a', function (e) { | |
_this.controller('a-clicked', e.target); | |
}); | |
/* Initialize */ | |
this.model(obj); | |
}; | |
// NOTE: For avoiding the duplicate logic, it is better to keep template clean. | |
Profile.template = HTML; | |
Profile.prototype.model = function (model_changed) { | |
filter the unchanged keys out; and | |
apply the changes to this._model | |
if (unchanged) return; | |
// sync with backend | |
model_changed._loading = true; | |
var _this = this; | |
$.ajax('/user/modify',{ | |
type: 'POST', | |
data: model_changed | |
}).fail(function (jqXHR) { | |
_this.view({_error: get error from jqXHR}); | |
}).always(function (){ | |
_this.view({_loading: false}); | |
}); | |
// update view | |
this.view(model_changed); | |
}; | |
Profile.prototype.view = function (view_changed) { | |
if (view_changed.nick !== undefined) { | |
this.$nick.text(view_changed.nick); | |
} | |
if (view_changed._loading !== undefined) { | |
this.$view.toggleClass('loading', view_changed._loading); | |
// clear up error if we start sending ajax | |
if (view_changed._loading) view_changed._error = ''; | |
} | |
if (view_changed._error !== undefined) { | |
this.$view.toggleClass('has-error', !!view_changed._error); | |
this.$error.text(view_changed._error); | |
} | |
}; | |
Profile.prototype.controller = function (event_name, target) { | |
switch (event_name) { | |
case 'a-clicked': | |
may check the locking state by a key in model here | |
may use target to do sub-dispatching | |
this.model({nick: this.$nick.val()}); | |
return; | |
} | |
}; | |
$(function() { | |
var profile = new Profile(); | |
$(document.body).append(profile.$view); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment