// As I mentioned with the debounce function, sometimes you don't
// get to plug into an event to signify a desired state -- if
// the event doesn't exist, you need to check for your desired
// state at intervals:
function poll(fn, callback, errback, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if (fn()) {
callback();
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
}
// Didn't match and too much time, reject!
else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
})();
}
// cookie
function cookie(key, value, hours, domain, path) {
var expires = new Date(),
pattern = "(?:; )?" + key + "=([^;]*);?",
regexp = new RegExp(pattern);
if (value) {
key += '=' + encodeURIComponent(value);
if (hours) {
expires.setTime(expires.getTime() + (hours * 3600000));
key += '; expires=' + expires.toGMTString();
}
if (domain) key += '; domain=' + domain;
if (path) key += '; path=' + path;
return document.cookie = key;
} else if (regexp.test(document.cookie)) return decodeURIComponent(RegExp["$1"]);
return false;
}
poll(function() {
console.log('Poll: check vkid cookie');
return cookie('vkid');
}, function() {
console.log('Poll: done, success callback');
}, function() {
console.log('Poll: error, failure callback');
}, 10000, 100);
var gOldOnError = window.onerror;
// Переопределить прошлый обработчик события.
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
if (gOldOnError)
// Вызвать прошлый обработчик события.
return gOldOnError(errorMsg, url, lineNumber);
// Просто запустить обработчик события по умолчанию.
return false;
}
function posttext() {
$.get(
'/main/',
{
text: $('#text').val(),
sender: 1,
thread: 1,
},
function(json) {
p = $('#chatul').append('<li>' + json.text + '</li>');
}
);
$('#text').val('');
};
function check() {
$.get(
'/check/',
{
thread:1
messages: $("#chatul") // что это, ты хочешь отправить на сервер jQuery выборку???
},
function(json) {
// if json.text !="" { где скобки??? может:
if (json.text != '') {
p = $('#chatul').append('<li>' + json.text + '</li>');
}
}
);
};
function Class() {}
console.log(typeof Class.prototype);
// "object"
// как видим, прототип объекта это тоже объект
console.log(typeof Class.prototype.constructor);
// "function"
// и у него уже есть метод constructor
console.log(Class.prototype.constructor === Class);
// true
// и он как раз и ссылается на саму функцию Class
// но когда расширяют прототип таким образом
Class.prototype = {
method: function() {},
method2: function() {}
}
// то переопределяют свойство prototype и связь с конструктором теряется
// и поэтому явно определяют конструктор
Class.prototype = {
constructor: Class,
method: function() {},
method2: function() {}
}
// для того, что бы этого не делать (не указывать явно ссылку на конструктор),
// правильнее было бы сделать так
function MyAwesomeClass() {}
MyAwesomeClass.prototype.method = function() {}
MyAwesomeClass.prototype.method2 = function() {}
var Collection = (function () {
var
url = '/Management/NestablePartical/',
el = '.dd';
function getData() {
$.get(url, function(response) {
render(response)
});
}
function render(data) { /* ... */ }
function event() { /* ... */ }
function init() { /* ... */ }
return {
// возвращаем только те методы, которые нужны вне модуля
init: init,
getData: getData
}
})();
<p class="center">Имя в игре</p>
<span id="check_login"></span>
<form method="POST" id="formx">
<input type="text" name="login" id="login" class="input"/>
<p class="center">Пароль в игре</p>
<input type="text" name="pass" id="pass" class="input"/>
<span id="submit"></span>
</form>
<script>
$(function() {
$("#formx").on("submit", function(e) {
e.preventDefault();
/* реализация ф-ции call() */
});
$("input[name=login]").on("keyup", function() {
checkLogin($(this).val());
});
$("#submit").on("click", pass_hash);
})
function checkLogin(login) {
$.post('/api/?alg=reg&action=save_validation', { login: login }, function(response) {
if (response) {
$("#check_login").html("<div class='message padd_top_10 padd_bot_10 red'><div><p>ВНИМАНИЕ! имя занято</p></div></div>");
$("#submit").html("");
} else {
$("#check_login").html("<div class='message padd_top_10 padd_bot_10 yellow'><div><p>Имя свободно</p></div></div>");
$("#submit").html('<div class="button orange"><input type="submit" name="" id= "btt" value="Выбрать имя"></div>');
}
});
}
function pass_hash() {
var data = {
login: $("#login").val(),
pass: hex_sha512($("#pass").val())
};
$.post('/api/?alg=reg&action=save', { data: data }, function(response) {
alert(response);
});
}
</script>
function Class() {}
// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
Class.extend = function(protoProps, staticProps) {
var parent = this, child, prop;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function() { return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
for (prop in parent) child[prop] = parent[prop];
for (prop in staticProps) child[prop] = staticProps[prop];
// Set the prototype chain to inherit from `parent`, without calling
// `parent` constructor function.
var Surrogate = function() { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
for (prop in protoProps) child.prototype[prop] = protoProps[prop];
// Save parent prototype
child.prototype.__super__ = parent.prototype;
return child;
};
var Model = Class.extend({
constructor: function() {
console.log("Model:constructor()");
}
});
var User = Model.extend({
constructor: function() {
this.__super__.constructor();
console.log("User:constructor()");
}
});
var SuperUser = User.extend({
constructor: function() {
this.__super__.constructor();
console.log("SuperUser:constructor()");
}
});
var supeUser = new SuperUser();
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(error) {
console.log(error.code);
}
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
}
function fail(error) {
console.log(error.code);
}