From e38bbdfe1c6ca3b2ca155231f7407a3bd1e7ef95 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 00:11:37 +0600 Subject: [PATCH 01/12] qunit --- .gitmodules | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7715e64 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "qunit"] + path = qunit + url = git://github.com/jquery/qunit.git From ce5137c8e60d54e8890106dcbc12c6913e65adbc Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 00:43:49 +0600 Subject: [PATCH 02/12] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=BE=D0=BD?= =?UTF-8?q?=D0=B0=D1=87=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitmodules | 3 - XHRobject.js | 21 ++++ collection.js | 91 +++++++++++++++ current-event.json | 4 + documentAction.js | 233 ++++++++++++++++++++++++++++++++++++++ event.js | 93 +++++++++++++++ events.js | 151 ++++++++++++++++++++++++ examples.js | 23 ++++ index.css | 28 +++++ index.html | 76 +++++++++++++ model.js | 62 ++++++++++ server.js | 4 + tests/EventsTest.html | 18 +++ tests/EventsTest.js | 78 +++++++++++++ tests/collectionTest.html | 17 +++ tests/collectionTest.js | 49 ++++++++ tests/eventTest.html | 16 +++ tests/eventTest.js | 24 ++++ tests/modelTest.html | 16 +++ tests/modelTest.js | 30 +++++ tests/serializeTest.html | 17 +++ tests/serializeTest.js | 10 ++ validation.js | 59 ++++++++++ 23 files changed, 1120 insertions(+), 3 deletions(-) delete mode 100644 .gitmodules create mode 100644 XHRobject.js create mode 100644 collection.js create mode 100644 current-event.json create mode 100644 documentAction.js create mode 100644 event.js create mode 100644 events.js create mode 100644 examples.js create mode 100644 index.css create mode 100644 index.html create mode 100644 model.js create mode 100644 server.js create mode 100644 tests/EventsTest.html create mode 100644 tests/EventsTest.js create mode 100644 tests/collectionTest.html create mode 100644 tests/collectionTest.js create mode 100644 tests/eventTest.html create mode 100644 tests/eventTest.js create mode 100644 tests/modelTest.html create mode 100644 tests/modelTest.js create mode 100644 tests/serializeTest.html create mode 100644 tests/serializeTest.js create mode 100644 validation.js diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 7715e64..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "qunit"] - path = qunit - url = git://github.com/jquery/qunit.git diff --git a/XHRobject.js b/XHRobject.js new file mode 100644 index 0000000..b77f36d --- /dev/null +++ b/XHRobject.js @@ -0,0 +1,21 @@ +(function (exports) { + "use strict"; + + exports.asyncXHR = function (method, url, callback, data) { + var xhr = new XMLHttpRequest(); + xhr.open(method, url, true); + + xhr.addEventListener('readystatechange', function () { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + callback(null, xhr.responseText); + } + else { + callback("error"); + } + } + }, false); + + xhr.send(data); + } +}(window)); \ No newline at end of file diff --git a/collection.js b/collection.js new file mode 100644 index 0000000..0ad8860 --- /dev/null +++ b/collection.js @@ -0,0 +1,91 @@ +(function (exports) { + "use strict"; + +var Collection = function (items) { + + this.items = []; + var key; + + for (key in items) { + if (items.hasOwnProperty(key)) { + this.items.push(items[key]); + } + } +}; + +exports.Collection = Collection; + +Collection.prototype.constructor = Collection; + +/** + * Сериализует коллекцию + * + * @return {JSON object} + * + */ +Collection.prototype.serialise = function () { + return JSON.stringify(this.items, 3); +} + +/** + * Добавляет в коллекцию объект + * + * @param {object} model + * + * @return {Collection} * @example + * + */ +Collection.prototype.add = function (model) { + + var temp = new this.constructor(this.items); + temp.items.push(model); + return temp; +}; + +/** + * @param {Function} selector + * + * @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter + * + * @example + * new Collection().filter(function (item) { + * return item.get('attendee').indexOf("me") !== -1; + * }); + * @return {Collection} + */ +Collection.prototype.filter = function (selector) { + + if (typeof selector !== "function") { + throw new Error('Argument must be function'); + } + + return new this.constructor(this.items.filter(selector)); +}; + +/** + * Принимает функцию сортировки и сортирует на основе ее + * + * @param {function} selector + * + * @return {Collection} * @example + * + */ +Collection.prototype.sort = function (selector) { + + if (typeof selector !== "function") { + throw new Error('Argument must be function'); + } + + return new this.constructor(this.items.sort(selector)); +}; + +Collection.prototype.reverse = function () { + + return new this.constructor(this.items.reverse()); +}; + +Collection.prototype.length = function (selector) { + + return this.items.length; +}; +}(window)); \ No newline at end of file diff --git a/current-event.json b/current-event.json new file mode 100644 index 0000000..af5f6a2 --- /dev/null +++ b/current-event.json @@ -0,0 +1,4 @@ +[ +{"name":"pewpew","start":"2012-11-07T10:18:39.207Z","end":"2012-11-07T10:18:39.207Z"}, +{"name":"Пара по веб-технологиям","start":"2012-11-20T12:50:40.207Z","end":"2012-11-20T12:50:50.207Z","location":"5 этаж","remindTime":10,"description":"Взять бумагу и ручку, не брать бук!"} +] \ No newline at end of file diff --git a/documentAction.js b/documentAction.js new file mode 100644 index 0000000..fe42474 --- /dev/null +++ b/documentAction.js @@ -0,0 +1,233 @@ +(function (exports) { + "use strict"; + + var ListOfEvents = new Events(); + var sortedList = new Events(); + + var filterOption = "all"; + var sortOption = "without"; + + document.body.addEventListener('load', initialise(), false); + + function initialise() { + asyncXHR('GET','http://localhost:8080/current-event.json', restoreState, null); + } + + /** + * Загружает свое состояние с сервера + * при отсутсвии соединения/страницы на сервере пытается подключиться через 5 минут снова + * +*/ + function restoreState(error, json) { + + document.querySelector("#notify").style.visibility = 'hidden'; + + if (error === "error") { + document.querySelector("#notifyError").visibility = 'visible'; + return; + } + + var parseObject = JSON.parse(json); + + for (var i=0; i < parseObject.length; i++) { + var newEvent = new Event(parseObject[i]).validate(); + ListOfEvents = ListOfEvents.add(newEvent); + }; + + changeDocument("sort"); + addListener(); +} + +/** + * Добавляет новое событие в список. Если установлены опции фильтрации и сортировки + * - то располагает элменты на странице, в с-ии с ними + * +*/ + function preventDefault() { + + var name = document.querySelector("#title").value, + start = document.querySelector("#from").value, + end = document.querySelector("#to").value, + location = document.querySelector("#location").value, + raiting = document.querySelector("#raiting").value, + description = document.querySelector("#description").value, + remindTime = document.querySelector("#remindTime").value; + + if (!validateTitle(name, document.querySelector('#title_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateDate(start, document.querySelector('#from_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateNumber(remindTime, document.querySelector('#remindTime_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + + var element = new Event({ + name: name, + start: start, + end: end, + location: location, + raiting: raiting, + description: description, + remindTime: remindTime + }).validate(); + + var result = ListOfEvents.add(element); + var data = result.serialise(); + + asyncXHR('POST','http://localhost:8080/current-event.json', function(error) { + + /*if (error === "error") { + alert("Не могу подключиться к северу. Попробуйте позже"); + return; + }*/ + + ListOfEvents = result; + changeDocument("sort"); + document.forms["form"].reset(); + }, data); + }; + + function filterEvents(listEvents) { + switch (filterOption) { + case "future": + return listEvents.coming(); + case "past": + return listEvents.past(); + default: + return listEvents; + } + } + + function sortEvents(listEvents) { + switch (sortOption) { + case "byName": + return ListOfEvents.sortByName(); + case "byStart": + return ListOfEvents.sortByTime(); + case "byRaiting": + return ListOfEvents.sortByRaiting(); + default: + return ListOfEvents; + } + } + +/** + * Сортирует и фильтрует события в соответствии с указанными опциями. + * + * @param {string} changeType - если указана строка "sort", то события также будут отсортированы, + * инчае - только отфильтрованы + * @return коллекция объектов типа event +*/ + + function changeDocument(changeType) { + var parent = document.querySelector(".collection"), + removeList = document.querySelector(".events"); + parent.removeChild(removeList); + + var addList = document.createElement('ul'); + addList.className = "events"; + + var fragment = document.createDocumentFragment(); + if (changeType === "sort") { + sortedList = sortEvents(ListOfEvents); + } + var filterList = filterEvents(sortedList); + + var length = filterList.length(); + + for (var i = 0; i < length; i++) + { + var element = filterList.items[i]; + var el = addLiElement(element); + addList.appendChild(el); + } + + var parent = document.querySelector(".collection"); + fragment.appendChild(addList); + parent.appendChild(fragment); +} + +/** + * Создает DOM-элемент типа li, заполняется полями из объекта + * + * @param {Event} element - объект типа Element + * + * @return Возвращает созданный дом-элемент типа li +*/ + + function addLiElement (element) { + var el = document.createElement('li'); + el.className = 'event_item'; + + var name = document.createElement('div'); + name.textContent = "Название: " + element.name; + + var start = document.createElement('div'); + start.textContent = "Начало: " + element.start; + + var end = document.createElement('div'); + end.textContent = "Окончание: " + element.end; + + var location = document.createElement('div'); + location.textContent = "Местоположение: " + element.location; + + var remindTime = document.createElement('div'); + remindTime.textContent = "Напомнить за: " + element.remindTime + "минут"; + + var description = document.createElement('div'); + description.textContent = "Описание: " + element.description; + + var raiting = document.createElement('div'); + raiting.textContent = "Рейтинг: " + element.raiting; + + el.appendChild(name); + el.appendChild(start); + el.appendChild(end); + el.appendChild(location); + el.appendChild(remindTime); + el.appendChild(description); + el.appendChild(raiting); + + return el; + }; + +/** + * Навешивает обработчики событий на страницу +*/ + function addListener() { + var name = document.querySelector("#title"); + var start = document.querySelector("#from"); + var remindTime = document.querySelector("#remindTime"); + var filters = document.querySelectorAll('.filter'); + var sort = document.querySelectorAll('.sort'); + var button = document.querySelector("#addButton"); + + name.addEventListener('blur', function(event) { + var cur = event.currentTarget; + validateTitle(cur.value, document.querySelector('#title_help')); + }); + + start.addEventListener('blur', function (event) { + var cur = event.currentTarget; + validateDate(cur.value, document.querySelector('#from_help')); + }); + + remindTime.addEventListener('blur', function (event) { + var cur = event.currentTarget; + validateNumber(remindTime.value, document.querySelector('#remindTime_help')); + }); + + for (var i=0; i < filters.length; i++) { + filters[i].addEventListener('change', function (event) { + filterOption = document.querySelector('input[name="filter"]:checked').value; + changeDocument("filter"); + }); + } + + for (var i=0; i < sort.length; i++) { + sort[i].addEventListener('change', function(event) { + sortOption = document.querySelector('input[name="sort"]:checked').value; + changeDocument("sort"); + }); + } + + button.addEventListener('click', preventDefault); + } + +}(window)); \ No newline at end of file diff --git a/event.js b/event.js new file mode 100644 index 0000000..f96a339 --- /dev/null +++ b/event.js @@ -0,0 +1,93 @@ +(function (exports) { + "use strict"; + + exports.isDate = function (date) { + + if (typeof date === 'undefined') { + return false; + } + if (typeof date.getMonth !== 'function') { + return false; + } + if (isNaN(date.getMonth())) { + return false; + } + return true; + }; + + exports.inherits = function (constructor, superconstructor) { + + var Func = function () { }; + + Func.prototype = superconstructor.prototype; + constructor.prototype = new Func(); + }; + + exports.Event = function (data) { + + Model.apply(this, arguments); + + if (typeof data.start !== undefined) { + this.start = new Date(this.start); + } + if (typeof data.end !== undefined) { + this.end = new Date(this.end); + } + }; + + inherits(Event, Model); + +/** + * Валидирует объект event, либо undefined, если в объекте отсутвуют обязательные поля + * eventObject{ + * name - название события + * start - начало + * end - окончание + * location - место + * remindTime - за сколько минут до события напомнить + * description - описание + * raiting - важность события + * } + + * @param {object} obj Объект + * @example + * Event({ + * name: "Пара по веб-технологиям", + * start: new Date("2012-10-20 10:00:00"), + * end: new Date("2012-10-20 12:50:00"), + * location: "5 этаж", + * remindTime: 10, + * raiting:5, + * description: "Взять бумагу и ручку, не брать бук!" + * }) + * + * @return {Object} + */ + Event.prototype.validate = function () { + + var remindTime = this.remindTime || 0; + this.raiting = this.raiting || 0; + + if (!isDate(this.get("start"))) { + throw new Error('Field "start" must be Date format'); + } + + if (!isDate(this.end)) { + this.end = this.start; + } + + if (this.end < this.start) { + this.end = this.start; + } + + return { + "name": this.name || "(Нет темы)", + "start": this.start, + "end": this.end, + "location": this.location || "", + "remindTime": remindTime, + "description": this.description || "(отсутствует)", + "raiting": this.raiting + }; + }; +}(window)); \ No newline at end of file diff --git a/events.js b/events.js new file mode 100644 index 0000000..ef7fd9d --- /dev/null +++ b/events.js @@ -0,0 +1,151 @@ +(function (exports) { + "use strict"; + +exports.Events = function (data) { + + Collection.apply(this, arguments); +}; + +inherits(Events, Collection); + +Events.prototype.constructor = exports.Events; + +/** + * Возвращает прошедшие события, из items отсортированной по дате начала + * + * @param {events} - коллекция объектов типа event + * @return {Collection} - коллекция объектов типа event +*/ +Events.prototype.past = function () { + + return this.filter(function (events) { + return events.start < new Date(); + }); +}; + +/** + * Возвращает предстоящие события, + * из items, отсортированной по дате начала + * + * @return {Collection} - коллекция объектов типа event +*/ +Events.prototype.coming = function () { + + return this.filter(function (events) { + return events.start > new Date(); + }); +}; + +/** + * Возвращает события, которые произойдут через опр период времени, + * из items, отсортированной по дате начала + * + * @param {number} days - период (в днях) времени + * + * @return коллекция объектов типа event +*/ +Events.prototype.comeThrough = function (days) { + + var now = new Date(); + now.setDate(now.getDate() + days); + + var result = this.coming() + .filter(function (events) { + return events.start < now; + }); + + return result; +}; + +Events.prototype.byEndTime = function () { + + return this.sort(function (a, b) { + return a.end - b.end; + }); +}; + +Events.prototype.byRaiting = function () { + + return this.sort(function (a, b) { + return a.raiting - b.raiting; + }); +}; + +Events.prototype.byStartTime = function () { + + return this.sort(function (a, b) { + return a.start - b.start; + }); +}; + +Events.prototype.byName = function () { + + return this.sort(function (a, b) { + return a.name - b.name; + }); +}; + +/** + * Возвращает события,из items отсортированной по дате начала по возр/убыв + * от старых обытий к новым / наоборот. + * По умолчанию сортирует в порядке возрастания + * + * @param {bool} isAscending - необязательный параметр - указывает порядок сортировки. + * при отсутсвии сортируется по возрастанию. + * + * @return {Collection} - Новый объект типа Collection +*/ +Events.prototype.sortByName = function (isAscending) { + + isAscending = isAscending || false; + + if (isAscending) { + return this.byName(); + } + return this.byName() + .reverse(); +}; + +/** + * Возвращает события,из items отсортированной по названию по возр/убыв + * По умолчанию сортирует в порядке возрастания + * + * @param {bool} isAscending - необязательный параметр - указывает порядок сортировки. + * при отсутсвии сортируется по возрастанию. + * + * @return {Collection} - Новый объект типа Collection +*/ +Events.prototype.sortByTime = function (isAscending) { + + isAscending = isAscending || false; + + if (isAscending) { + return this + .byStartTime().reverse(); + } + return this.byStartTime(); +}; + +/** + * Возвращает события, из items, отсортированной по рейтингу по убыв/возрастанию + * от событий с более высоким рейтингом к самому низко приоритетному / наоборот. + * По умолчанию сортирует в порядке убывания + * + * @param {bool} isAscending - необязательный параметр - указывает порядок сортировки. + * при отсутствии сортируется по убыванию. + * + * @return {COllection} - Новый объект типа Collection +*/ +Events.prototype.sortByRaiting = function (isAscending) { + + isAscending = isAscending || false; + + if (isAscending) { + return this + .byRaiting() + .reverse(); + } + return this + .byRaiting(); +}; +}(window)); \ No newline at end of file diff --git a/examples.js b/examples.js new file mode 100644 index 0000000..8aa58ae --- /dev/null +++ b/examples.js @@ -0,0 +1,23 @@ +var examples = [ + { name: "Пара по веб-технологиям", start: new Date("2012-10-20 10:00:00"), end: new Date("2012-10-20 12:50:00"), location: "5 этаж", remindTime: 10, description: "Взять бумагу и ручку, не брать бук!" }, + { name: "День зимы", start: new Date("2012-10-27 06:00:00"), end: new Date("2012-10-27 12:00:00"), location: "Скандинавия", description: "Кататься ^_^" }, + { name: "День инженера механика", start: new Date("2012-10-29 10:00:00"), end: new Date("2012-10-29 15:00:00"), location: "9 этаж", remindTime: 10 }, + { name: "День вегана", start: new Date("2012-11-1 10:00:00"), end: new Date("2012-10-1 23:00"), location: "Дома", description: "Be vegan =)" }, + { name: "День журналисты", start: new Date("2012-11-8 10:00:00"), location: "Китай", remindTime: 10, description: "Поздравить Олежу" }, + { name: "Всемирный день борьбы с диабетом", start: new Date("2012-11-14 12:00") }, + { name: "Международный день отказа от курения", start: new Date("2012-11-15 12:00"), description: "Поздравить Сашку)" }, + { name: "День защиты черных котов", start: new Date("2012-11-17 14:00:00"), location: "Италия", remindTime: 50, description: "Котэ" }, + { name: "Всемирный день туалетов", start: new Date("2012-11-19 15:00:00"), location: "МИр", description: "о_О" }, + { name: "День революции", start: new Date("2012-11-20 12:00:00"), location: "Мексика"}, + { name: "День сладостей", start: new Date("2012-10-20 15:00:00"), location: "США", remindTime: 10, description: "Приготовить вкусняшки" }, + { name: "Ерофеев день", start: new Date("2012-10-17 16:00:00"), location: "Россия", description: "Лисики" }, + { name: "Утиный фестиваль", start: new Date("2012-10-13 12:00:00"), location: "Италия", description: "Все в Италию!" }, + { name: "Дент ребенка", start: new Date("2012-10-12 14:00:00"), location: "Бразилия" }, + { name: "День физкультуры", start: new Date("2012-10-8 12:00:00"), location: "Япония"}, + { name: "Всемирный день животных", start: new Date("2012-10-4 12:00:00 ")}, + { name: "День сакэ в Японии", start: new Date("2012-10-1 14:00:00") }, + { name: "День моря", start: new Date("2012-09-27 15:00:00") }, + { name: "День комиксов", start: new Date("2012-09-25 15:00:00"), location: "США"}, + { name: "День почитания пожилых людей", start: new Date("2012-09-17 16:00:00")}, + { name: "Международный жень демократии", start: new Date("2012-09-15 17:00:00")} +]; \ No newline at end of file diff --git a/index.css b/index.css new file mode 100644 index 0000000..1134963 --- /dev/null +++ b/index.css @@ -0,0 +1,28 @@ +body{ text-align: left;} +#frame { + display: inline-block; + float: left; + text-align: right; +} +.help { + color: red; + visibility : hidden; + min-height: 25px; +} +.event_item{ +} +.collection{ + float: left; + text-align: left; + margin-left: 50px; +} +.select{ + text-align: left; +} +.selecter{ + color: blue; +} +#notifyError{ + visibility: hidden; +} + diff --git a/index.html b/index.html new file mode 100644 index 0000000..6ac7fab --- /dev/null +++ b/index.html @@ -0,0 +1,76 @@ + + + + + Календарь событий + + + +
+
+
Название: +
+
С:
+
По:
+
Место:
+
Важность события: + +
+
Описание: + +
+
Напомнить за: минут +
+ + +
+
+
Выбрать
+
+
+ +
Отсортировать по
+
+
+
+ +
+
+
+
Введите название события
+
Введите корректную дату
+
Введите корректную дату
+
D
+
D
+
D
+
D
+
Введите корректное число
+
+ +
+
    +
    +
    +
    +
    +
    + + + + + + + + + + \ No newline at end of file diff --git a/model.js b/model.js new file mode 100644 index 0000000..963a925 --- /dev/null +++ b/model.js @@ -0,0 +1,62 @@ +(function (exports) { + "use strict"; + +/** + * Абстрактный конструктор, принимает объект и создает абстрактный объект для работы + * + * @param {Object} attributes + * + * @example + * item.set({title: "March 20", content: "In his eyes she eclipses..."}); + */ +exports.Model = function (data) { + + var key; + + for (key in data) { + if (data.hasOwnProperty(key)) { + this[key] = data[key]; + } + } +}; + + +/** + * Сеттер - устанавливает аттрибуты и значения атрибутов, в соответсвии с принятым в качестве параметра объектом + * + * @param {Object} attributes + * + * @example + * item.set({title: "March 20", content: "In his eyes she eclipses..."}); + */ +Model.prototype.set = function (attributes) { + + var key; + + for (key in attributes) { + if (attributes.hasOwnProperty(key)) { + this[key] = attributes[key]; + } + } +}; + +/** + * Геттер - возвращает запрашиваемое свойство у объекта + * + * @param {Object} attributes + */ +Model.prototype.get = function (attribute) { + + if (this.hasOwnProperty(attribute)) { + return this[attribute]; + } + + return undefined; +}; +/** + * @param {Object} attributes + */ +Model.prototype.validate = function (attributes) { + throw new Error('this is Abstract method'); +}; +}(window)); \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 0000000..27e0e31 --- /dev/null +++ b/server.js @@ -0,0 +1,4 @@ +var connect = require('connect'); +connect.createServer( + connect.static(__dirname) +).listen(8080); \ No newline at end of file diff --git a/tests/EventsTest.html b/tests/EventsTest.html new file mode 100644 index 0000000..dbafb9e --- /dev/null +++ b/tests/EventsTest.html @@ -0,0 +1,18 @@ + + + + + Тестирование класса Events (Collection) + + + + + + + + + + +
    + + diff --git a/tests/EventsTest.js b/tests/EventsTest.js new file mode 100644 index 0000000..87cc5aa --- /dev/null +++ b/tests/EventsTest.js @@ -0,0 +1,78 @@ +function getString(event) { + "use strict"; + + return "\n" + event.name + "\n" + " начало: " + event.start + "\n" + + " конец: " + event.end + "\n" + + " место события: " + event.location + " напомнить за " + event.remindTime + " минут" + "\n" + + " описание: " + event.description + "\n"; +} + +test("Testing inherits Events from Collection", function () { + "use strict"; + + var collection = new Events(examples), + element = {title: "March 20", content: "In his eyes she eclipses..."}, + result = collection.add(element); + + examples.push(element); + + deepEqual(result.items, examples, "Two objects can be the same in value"); +}); + +test("Testing past in Events", function () { + "use strict"; + + var collection = new Events(examples), + result = collection.past(); + + console.log("Result: " + result.items.map(function (event) { + return getString(event); + })); + + console.log("--------------\n"); + ok("1" === "1", "Two objects can be the same in value"); +}); + +test("Testing coming in Events", function () { + "use strict"; + + var collection = new Events(examples), + result = collection.coming(); + + console.log("Result: " + result.items.map(function(event) { + return getString(event); + })); + + console.log("--------------\n"); + ok("1" === "1", "Two objects can be the same in value"); +}); + +test("Testing comeThrough in Events", function () { + "use strict"; + + var collection = new Events(examples), + result = collection.comeThrough(10); + + console.log("Result: " + result.items.map(function (event) { + return getString(event); + })); + + console.log("--------------\n"); + ok("1" === "1", "Two objects can be the same in value"); +}); + +test("Testing sortBytime in Events", function () { + "use strict"; + + var collection = new Events(examples), + result = collection.byStartTime(); + + console.log("Result: " + result.items.map(function (event) { + return getString(event); + })); + + console.log("--------------\n"); + ok("1" === "1", "Two objects can be the same in value"); +}); + + diff --git a/tests/collectionTest.html b/tests/collectionTest.html new file mode 100644 index 0000000..1ae6ec6 --- /dev/null +++ b/tests/collectionTest.html @@ -0,0 +1,17 @@ + + + + + Тестирование класса Collection + + + + + + + + + +
    + + diff --git a/tests/collectionTest.js b/tests/collectionTest.js new file mode 100644 index 0000000..bef8374 --- /dev/null +++ b/tests/collectionTest.js @@ -0,0 +1,49 @@ +test("Create object Collection", function () { + "use strict"; + + var result = new Collection(examples); + + ok(result.items[0].name == examples[0].name, "Passed!"); +}); + +test("Testing for creating new Collection in constructor", function () { + "use strict"; + + var result = new Collection(examples); + result.items.pop(); + + ok(result.items.length !== examples.length, "Passed!"); +}); + +test("Add func in Collection", function () { + "use strict"; + + var collection = new Collection(examples), + element = {title: "March 20", content: "In his eyes she eclipses..."}, + result = collection.add(element); + + examples.push(element); + + deepEqual(result.items, examples, "Two objects can be the same in value"); +}); + +test("Test Collection", function () { + "use strict"; + + var collection = new Collection(), + element = {title: "March 20", content: "In his eyes she eclipses..."}, + result = collection.add(element); + + deepEqual(result.items, [element], "Two objects can be the same in value"); +}); + +test("Filter func in Collection", function () { + "use strict"; + + var collection = new Collection(examples), + result = collection.filter(function (item) { + return item.name === "День зимы"; + }); + + ok(result.items.length !== examples.length, "Passed"); +}); diff --git a/tests/eventTest.html b/tests/eventTest.html new file mode 100644 index 0000000..d8284b1 --- /dev/null +++ b/tests/eventTest.html @@ -0,0 +1,16 @@ + + + + + Тестирование класса Event и наследования от класса Model + + + + + + + + +
    + + diff --git a/tests/eventTest.js b/tests/eventTest.js new file mode 100644 index 0000000..4c87609 --- /dev/null +++ b/tests/eventTest.js @@ -0,0 +1,24 @@ +test("Create object Event using Model constructor", function () { + "use strict"; + + var item = new Event({title: "March 20", content: "In his eyes she eclipses..."}); + + ok(item.title === "March 20", "Passed!"); +}); + +test("Testing inherits Event from Model", function () { + "use strict"; + + var item = new Event({title: "March 20", content: "In his eyes she eclipses..."}); + + ok(item.get("title") === "March 20", "Passed!"); +}); + +test("Test for validate method", function () { + "use strict"; + + var itm = new Event({name: "hello", start: new Date("2012/10/20 10:00:00")}), + valide = itm.validate(); + + ok(valide.name === "hello", "Passed!"); +}); diff --git a/tests/modelTest.html b/tests/modelTest.html new file mode 100644 index 0000000..978bab0 --- /dev/null +++ b/tests/modelTest.html @@ -0,0 +1,16 @@ + + + + + Тестирование класса Model + + + + + + + + +
    + + diff --git a/tests/modelTest.js b/tests/modelTest.js new file mode 100644 index 0000000..c322f9e --- /dev/null +++ b/tests/modelTest.js @@ -0,0 +1,30 @@ +test("Testing qunit", function () { + "use strict"; + + ok( "1" == "1", "Passed!"); +}); + +test("Creating absract object Model", function () { + "use strict"; + + var item = new Model({title: "March 20", content: "In his eyes she eclipses..."}); + ok(item.title === "March 20", "Passed!"); +}); + + +test("Testing setter for Model", function () { + "use strict"; + + var item = new Model(); + item.set({title: "March 20", content: "In his eyes she eclipses..."}); + ok(item.title === "March 20", "Passed!"); +}); + +test("Testing getter for Model", function () { + "use strict"; + + var item = new Model(); + item.set({title: "March 20", content: "In his eyes she eclipses..."}); + + ok(item.get("title") === "March 20", "Passed!"); +}); \ No newline at end of file diff --git a/tests/serializeTest.html b/tests/serializeTest.html new file mode 100644 index 0000000..34de4fa --- /dev/null +++ b/tests/serializeTest.html @@ -0,0 +1,17 @@ + + + + + Тестирование класса Collection + + + + + + + + + +
    + + diff --git a/tests/serializeTest.js b/tests/serializeTest.js new file mode 100644 index 0000000..f267afe --- /dev/null +++ b/tests/serializeTest.js @@ -0,0 +1,10 @@ +test("Create object Event using Model constructor", function () { + "use strict"; + + var item = new Collection([{"name":"pewpew","start":"2012-11-07T10:18:39.207Z","end":"2012-11-07T10:18:39.207Z"}]) + .serialise(); + + ok(item === '[{"name":"pewpew","start":"2012-11-07T10:18:39.207Z","end":"2012-11-07T10:18:39.207Z"}]'); +}); + +'' \ No newline at end of file diff --git a/validation.js b/validation.js new file mode 100644 index 0000000..9835656 --- /dev/null +++ b/validation.js @@ -0,0 +1,59 @@ +(function (exports) { + "use strict"; + + exports.ListOfEvents = new Events(); + + exports.showError = function (isError, helpText) { + + if (isError) { + if (helpText.style.visibility !== 'visible') { + helpText.style.visibility = 'visible'; + } + return; + } + + if (helpText.style.visibility !== 'hidden') { + helpText.style.visibility = 'hidden'; + } + }; + + exports.validateTitle = function (input, helpText) { + + if (input.length === 0) { + showError(true, helpText); + return false; + } + + showError(false, helpText); + return true; + }; + + exports.validateDate = function (input, helpText) { + + if (!isDate(new Date(input))) { + showError(true, helpText); + return false; + } + + showError(false, helpText); + return true; + }; + + exports.validateNumber = function (input, helpText) { + + if (typeof +input !== "number") { + if (typeof input !== "undefined") { + showError(true, helpText); + return false; + } + } + + if (+input < 0) { + showError(true, helpText); + return false; + } + + showError(false, helpText); + return true; + }; +}(window)); \ No newline at end of file From 972c1c5a84732968af07748601781164a22df1ee Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 05:49:31 +0600 Subject: [PATCH 03/12] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=81=D0=BE=D1=82=D0=BE=D1=8F=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B8=20=D1=81=D0=BE=D1=80=D1=82=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B5=D1=85=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=B0=20jQuery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- documentAction.js | 90 +++++++++++++++++++++++------------------------ index.html | 1 + 2 files changed, 46 insertions(+), 45 deletions(-) diff --git a/documentAction.js b/documentAction.js index fe42474..b55fb8c 100644 --- a/documentAction.js +++ b/documentAction.js @@ -20,10 +20,10 @@ */ function restoreState(error, json) { - document.querySelector("#notify").style.visibility = 'hidden'; + $("#notify").hide(); if (error === "error") { - document.querySelector("#notifyError").visibility = 'visible'; + $('#notifyError').show(); return; } @@ -45,17 +45,17 @@ */ function preventDefault() { - var name = document.querySelector("#title").value, - start = document.querySelector("#from").value, - end = document.querySelector("#to").value, - location = document.querySelector("#location").value, - raiting = document.querySelector("#raiting").value, - description = document.querySelector("#description").value, - remindTime = document.querySelector("#remindTime").value; + var name = $("#title").val(), + start = $("#from").val(), + end = $("#to").val(), + location = $("#location").val(), + raiting = $("#raiting").val(), + description = $("#description").val(), + remindTime = $("#remindTime").val(); - if (!validateTitle(name, document.querySelector('#title_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; - if (!validateDate(start, document.querySelector('#from_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; - if (!validateNumber(remindTime, document.querySelector('#remindTime_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateTitle(name, $('#title_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateDate(start, $('#from_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateNumber(remindTime, $('#remindTime_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; var element = new Event({ name: name, @@ -116,12 +116,12 @@ */ function changeDocument(changeType) { - var parent = document.querySelector(".collection"), - removeList = document.querySelector(".events"); - parent.removeChild(removeList); + var $removeList = $(".events").eq(0); + $removeList.remove(); - var addList = document.createElement('ul'); - addList.className = "events"; + var $addList = $('
      ', { + class: "events" + }); var fragment = document.createDocumentFragment(); if (changeType === "sort") { @@ -134,12 +134,12 @@ for (var i = 0; i < length; i++) { var element = filterList.items[i]; - var el = addLiElement(element); - addList.appendChild(el); + var $el = addLiElement(element); + $el.appendTo($addList); } var parent = document.querySelector(".collection"); - fragment.appendChild(addList); + $addList.appendTo(fragment); parent.appendChild(fragment); } @@ -152,39 +152,39 @@ */ function addLiElement (element) { - var el = document.createElement('li'); - el.className = 'event_item'; + var $el = $('
    • ', { + className: 'event_item' + }); - var name = document.createElement('div'); - name.textContent = "Название: " + element.name; + var $name = $('
      ', { + text: "Название: " + element.name + }).appendTo($el); - var start = document.createElement('div'); - start.textContent = "Начало: " + element.start; + var $start = $('
      ', { + text: "Начало: " + element.start + }).appendTo($el); - var end = document.createElement('div'); - end.textContent = "Окончание: " + element.end; + var $end = $('
      ', { + text: "Окончание: " + element.end + }).appendTo($el); - var location = document.createElement('div'); - location.textContent = "Местоположение: " + element.location; + var $location = $('
      ', { + text: "Местоположение: " + element.location + }).appendTo($el); - var remindTime = document.createElement('div'); - remindTime.textContent = "Напомнить за: " + element.remindTime + "минут"; + var $remindTime = $('
      ', { + text: "Напомнить за: " + element.remindTime + "минут" + }).appendTo($el); - var description = document.createElement('div'); - description.textContent = "Описание: " + element.description; - - var raiting = document.createElement('div'); - raiting.textContent = "Рейтинг: " + element.raiting; + var $description = $('
      ', { + text: "Описание: " + element.description + }).appendTo($el); - el.appendChild(name); - el.appendChild(start); - el.appendChild(end); - el.appendChild(location); - el.appendChild(remindTime); - el.appendChild(description); - el.appendChild(raiting); + var $raiting = $('
      ', { + text: "Рейтинг: " + element.raiting + }).appendTo($el); - return el; + return $el; }; /** diff --git a/index.html b/index.html index 6ac7fab..e29f667 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,7 @@
      + From 20fc2dd4dbce0e7eeb4709872a1ccb54fa919cc6 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 06:08:07 +0600 Subject: [PATCH 04/12] =?UTF-8?q?=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=D0=B8=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82?= =?UTF-8?q?=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- documentAction.js | 57 +++++++++++++++++++++++------------------------ validation.js | 9 ++------ 2 files changed, 30 insertions(+), 36 deletions(-) diff --git a/documentAction.js b/documentAction.js index b55fb8c..63d7a7e 100644 --- a/documentAction.js +++ b/documentAction.js @@ -191,43 +191,42 @@ * Навешивает обработчики событий на страницу */ function addListener() { - var name = document.querySelector("#title"); - var start = document.querySelector("#from"); - var remindTime = document.querySelector("#remindTime"); - var filters = document.querySelectorAll('.filter'); - var sort = document.querySelectorAll('.sort'); - var button = document.querySelector("#addButton"); - - name.addEventListener('blur', function(event) { - var cur = event.currentTarget; - validateTitle(cur.value, document.querySelector('#title_help')); + var $name = $("#title"); + var $start = $("#from"); + var $remindTime = $("#remindTime"); + var $filters = $('.filter'); + var $sort = $('.sort'); + var $button = $("#addButton"); + + $name.on('blur', function($event) { + var cur = $event.currentTarget; + validateTitle(cur.value, $('#title_help')); }); - start.addEventListener('blur', function (event) { - var cur = event.currentTarget; - validateDate(cur.value, document.querySelector('#from_help')); + $start.on('blur', function ($event) { + var cur = $event.currentTarget; + validateDate(cur.value, $('#from_help')); }); - remindTime.addEventListener('blur', function (event) { - var cur = event.currentTarget; - validateNumber(remindTime.value, document.querySelector('#remindTime_help')); + $remindTime.on('blur', function ($event) { + var cur = $event.currentTarget; + validateNumber(remindTime.value, $('#remindTime_help')); }); - for (var i=0; i < filters.length; i++) { - filters[i].addEventListener('change', function (event) { - filterOption = document.querySelector('input[name="filter"]:checked').value; - changeDocument("filter"); - }); - } + $filters.each(function(index) { + $(this).on('change', function ($event) { + filterOption = document.querySelector('input[name="filter"]:checked').value; + changeDocument("filter"); + })}); + + $sort.each(function(index) { + $(this).on('change', function ($event) { + sortOption = document.querySelector('input[name="sort"]:checked').value; + changeDocument("sort"); + })}); - for (var i=0; i < sort.length; i++) { - sort[i].addEventListener('change', function(event) { - sortOption = document.querySelector('input[name="sort"]:checked').value; - changeDocument("sort"); - }); - } - button.addEventListener('click', preventDefault); + $button.on('click', preventDefault); } }(window)); \ No newline at end of file diff --git a/validation.js b/validation.js index 9835656..41fd872 100644 --- a/validation.js +++ b/validation.js @@ -6,15 +6,10 @@ exports.showError = function (isError, helpText) { if (isError) { - if (helpText.style.visibility !== 'visible') { - helpText.style.visibility = 'visible'; - } + helpText.show(); return; } - - if (helpText.style.visibility !== 'hidden') { - helpText.style.visibility = 'hidden'; - } + helpText.hide(); }; exports.validateTitle = function (input, helpText) { From f90678a3e90673d8e04f4fc8bb42d7368f477bb4 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 20:38:17 +0600 Subject: [PATCH 05/12] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D0=B0=D0=BD=D0=BE=20=D0=B2=20Ajax=20=D0=A0=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20=D0=B2=20IE8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- XHRobject.js | 21 ---------- current-event.json | 4 +- datepicker.js | 6 +++ documentAction.js | 86 ++++++++++++++++++++------------------- index.html | 4 +- modernizr.custom.89360.js | 4 ++ 6 files changed, 60 insertions(+), 65 deletions(-) delete mode 100644 XHRobject.js create mode 100644 datepicker.js create mode 100644 modernizr.custom.89360.js diff --git a/XHRobject.js b/XHRobject.js deleted file mode 100644 index b77f36d..0000000 --- a/XHRobject.js +++ /dev/null @@ -1,21 +0,0 @@ -(function (exports) { - "use strict"; - - exports.asyncXHR = function (method, url, callback, data) { - var xhr = new XMLHttpRequest(); - xhr.open(method, url, true); - - xhr.addEventListener('readystatechange', function () { - if (xhr.readyState === 4) { - if (xhr.status === 200) { - callback(null, xhr.responseText); - } - else { - callback("error"); - } - } - }, false); - - xhr.send(data); - } -}(window)); \ No newline at end of file diff --git a/current-event.json b/current-event.json index af5f6a2..6610503 100644 --- a/current-event.json +++ b/current-event.json @@ -1,4 +1,4 @@ [ -{"name":"pewpew","start":"2012-11-07T10:18:39.207Z","end":"2012-11-07T10:18:39.207Z"}, -{"name":"Пара по веб-технологиям","start":"2012-11-20T12:50:40.207Z","end":"2012-11-20T12:50:50.207Z","location":"5 этаж","remindTime":10,"description":"Взять бумагу и ручку, не брать бук!"} +{"name":"pewpew","start":"2012/11/07 10:18","end":"2012/11/07 10:18"}, +{"name":"Пара по веб-технологиям","start":"2012/11/20 12:50","end":"2012/11/20 12:50","location":"5 этаж","remindTime":10,"description":"Взять бумагу и ручку, не брать бук!"} ] \ No newline at end of file diff --git a/datepicker.js b/datepicker.js new file mode 100644 index 0000000..72221d7 --- /dev/null +++ b/datepicker.js @@ -0,0 +1,6 @@ +Modernizr.load({ + test: Modernizr.inputtypes.date, + nope: function () { + $("input[type='date']").datepicker(); + } + }); \ No newline at end of file diff --git a/documentAction.js b/documentAction.js index 63d7a7e..596f8a0 100644 --- a/documentAction.js +++ b/documentAction.js @@ -1,4 +1,4 @@ -(function (exports) { +$(function (exports) { "use strict"; var ListOfEvents = new Events(); @@ -7,37 +7,38 @@ var filterOption = "all"; var sortOption = "without"; - document.body.addEventListener('load', initialise(), false); + $(document.body).on('load', initialise()); - function initialise() { - asyncXHR('GET','http://localhost:8080/current-event.json', restoreState, null); - } - - /** +/** * Загружает свое состояние с сервера * при отсутсвии соединения/страницы на сервере пытается подключиться через 5 минут снова * */ - function restoreState(error, json) { - - $("#notify").hide(); + function initialise() { - if (error === "error") { - $('#notifyError').show(); - return; + $.ajax({ + dataType: 'json', + url: 'http://localhost:8080/current-event.json', + success: function(jqXHR) { + for (var i = 0; i < jqXHR.length; i++) + { + var newEvent = new Event(jqXHR[i]).validate(); + ListOfEvents = ListOfEvents.add(newEvent); + }; + changeDocument("sort"); + addListener(); + }, + error: function() { + if (error === "error") { + $('#notifyError').show(); + return; + } + }}) + .always(function() { + $("#notify").hide(); + }); } - var parseObject = JSON.parse(json); - - for (var i=0; i < parseObject.length; i++) { - var newEvent = new Event(parseObject[i]).validate(); - ListOfEvents = ListOfEvents.add(newEvent); - }; - - changeDocument("sort"); - addListener(); -} - /** * Добавляет новое событие в список. Если установлены опции фильтрации и сортировки * - то располагает элменты на странице, в с-ии с ними @@ -68,19 +69,22 @@ }).validate(); var result = ListOfEvents.add(element); - var data = result.serialise(); - - asyncXHR('POST','http://localhost:8080/current-event.json', function(error) { - /*if (error === "error") { - alert("Не могу подключиться к северу. Попробуйте позже"); - return; - }*/ - - ListOfEvents = result; - changeDocument("sort"); - document.forms["form"].reset(); - }, data); + $.ajax({ + type: 'POST', + url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', + data: result.serialise(), + error: function() { + /*if (error === "error") { + alert("Не могу подключиться к северу. Попробуйте позже"); + return; + }*/ + }}) + .always(function() { + ListOfEvents = result; + changeDocument("sort"); + document.forms["form"].reset(); + }); }; function filterEvents(listEvents) { @@ -116,7 +120,7 @@ */ function changeDocument(changeType) { - var $removeList = $(".events").eq(0); + var $removeList = $(".events"); $removeList.remove(); var $addList = $('
        ', { @@ -138,9 +142,9 @@ $el.appendTo($addList); } - var parent = document.querySelector(".collection"); + var $parent = $(".collection"); $addList.appendTo(fragment); - parent.appendChild(fragment); + $parent.append(fragment); } /** @@ -215,13 +219,13 @@ $filters.each(function(index) { $(this).on('change', function ($event) { - filterOption = document.querySelector('input[name="filter"]:checked').value; + filterOption = $('input[name="filter"]:checked').val(); changeDocument("filter"); })}); $sort.each(function(index) { $(this).on('change', function ($event) { - sortOption = document.querySelector('input[name="sort"]:checked').value; + sortOption = $('input[name="sort"]:checked').val(); changeDocument("sort"); })}); diff --git a/index.html b/index.html index e29f667..a9b3120 100644 --- a/index.html +++ b/index.html @@ -66,12 +66,14 @@
      + + + - \ No newline at end of file diff --git a/modernizr.custom.89360.js b/modernizr.custom.89360.js new file mode 100644 index 0000000..585f292 --- /dev/null +++ b/modernizr.custom.89360.js @@ -0,0 +1,4 @@ +/* Modernizr 2.6.2 (Custom Build) | MIT & BSD + * Build: http://modernizr.com/download/#-input-inputtypes-shiv-cssclasses-load + */ +;window.Modernizr=function(a,b,c){function v(a){j.cssText=a}function w(a,b){return v(prefixes.join(a+";")+(b||""))}function x(a,b){return typeof a===b}function y(a,b){return!!~(""+a).indexOf(b)}function z(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:x(f,"function")?f.bind(d||b):f}return!1}function A(){e.input=function(c){for(var d=0,e=c.length;d",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+q.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f Date: Fri, 16 Nov 2012 20:39:38 +0600 Subject: [PATCH 06/12] . --- documentAction.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentAction.js b/documentAction.js index 596f8a0..8ea934c 100644 --- a/documentAction.js +++ b/documentAction.js @@ -18,7 +18,7 @@ $.ajax({ dataType: 'json', - url: 'http://localhost:8080/current-event.json', + url: 'http://http://yunnii.github.com/dz-7-jquery/current-event.json', success: function(jqXHR) { for (var i = 0; i < jqXHR.length; i++) { From fdb3c76a0de19c92f5f60620310543e0fbece651 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 20:40:41 +0600 Subject: [PATCH 07/12] -__- --- documentAction.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentAction.js b/documentAction.js index 8ea934c..47a4cc5 100644 --- a/documentAction.js +++ b/documentAction.js @@ -18,7 +18,7 @@ $.ajax({ dataType: 'json', - url: 'http://http://yunnii.github.com/dz-7-jquery/current-event.json', + url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', success: function(jqXHR) { for (var i = 0; i < jqXHR.length; i++) { From 1db942599b5dd5e10b8fbb1ae48de9674a6189d1 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 20:54:36 +0600 Subject: [PATCH 08/12] . --- documentAction.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/documentAction.js b/documentAction.js index 47a4cc5..331de54 100644 --- a/documentAction.js +++ b/documentAction.js @@ -123,9 +123,8 @@ var $removeList = $(".events"); $removeList.remove(); - var $addList = $('
        ', { - class: "events" - }); + var $addList = $('
          ') + .addClass("events"); var fragment = document.createDocumentFragment(); if (changeType === "sort") { From 2363a745d87ad8181a9d187e98af9c4294c59fd1 Mon Sep 17 00:00:00 2001 From: yunnii Date: Fri, 16 Nov 2012 21:43:53 +0600 Subject: [PATCH 09/12] jslint --- datepicker.js | 8 ++-- documentAction.js | 99 +++++++++++++++++++++++------------------------ 2 files changed, 53 insertions(+), 54 deletions(-) diff --git a/datepicker.js b/datepicker.js index 72221d7..6d819a7 100644 --- a/datepicker.js +++ b/datepicker.js @@ -1,6 +1,6 @@ Modernizr.load({ - test: Modernizr.inputtypes.date, - nope: function () { - $("input[type='date']").datepicker(); + test: Modernizr.inputtypes.date, + nope: function () { + $("input[type='date']").datepicker(); } - }); \ No newline at end of file +}); \ No newline at end of file diff --git a/documentAction.js b/documentAction.js index 331de54..4b80fba 100644 --- a/documentAction.js +++ b/documentAction.js @@ -1,17 +1,16 @@ $(function (exports) { "use strict"; - var ListOfEvents = new Events(); - var sortedList = new Events(); - - var filterOption = "all"; - var sortOption = "without"; + var ListOfEvents = new Events(), + sortedList = new Events(), + filterOption = "all", + sortOption = "without"; $(document.body).on('load', initialise()); /** * Загружает свое состояние с сервера - * при отсутсвии соединения/страницы на сервере пытается подключиться через 5 минут снова + * при отсутствии соединения/страницы на сервере пытается подключиться через 5 минут снова * */ function initialise() { @@ -19,29 +18,28 @@ $.ajax({ dataType: 'json', url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', - success: function(jqXHR) { - for (var i = 0; i < jqXHR.length; i++) - { - var newEvent = new Event(jqXHR[i]).validate(); + success: function (jqXHR) { + var i, newEvent; + + for (i = 0; i < jqXHR.length; i++) { + newEvent = new Event(jqXHR[i]).validate(); ListOfEvents = ListOfEvents.add(newEvent); - }; + } changeDocument("sort"); addListener(); }, - error: function() { - if (error === "error") { - $('#notifyError').show(); - return; - } - }}) - .always(function() { - $("#notify").hide(); - }); - } - + error: function () { + $('#notifyError').show(); + return; + } + }) + .always(function () { + $("#notify").hide(); + }); + } /** * Добавляет новое событие в список. Если установлены опции фильтрации и сортировки - * - то располагает элменты на странице, в с-ии с ними + * - то располагает элементы на странице, в с-ии с ними * */ function preventDefault() { @@ -54,9 +52,9 @@ description = $("#description").val(), remindTime = $("#remindTime").val(); - if (!validateTitle(name, $('#title_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; - if (!validateDate(start, $('#from_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; - if (!validateNumber(remindTime, $('#remindTime_help'))) { alert("Событие не было добавлено. Ошибка"); return; }; + if (!validateTitle(name, $('#title_help'))) { alert("Событие не было добавлено. Ошибка"); return; } + if (!validateDate(start, $('#from_help'))) { alert("Событие не было добавлено. Ошибка"); return; } + if (!validateNumber(remindTime, $('#remindTime_help'))) { alert("Событие не было добавлено. Ошибка"); return; } var element = new Event({ name: name, @@ -74,18 +72,19 @@ type: 'POST', url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', data: result.serialise(), - error: function() { + error: function () { /*if (error === "error") { alert("Не могу подключиться к северу. Попробуйте позже"); return; }*/ - }}) - .always(function() { + } + }) + .always(function () { ListOfEvents = result; changeDocument("sort"); document.forms["form"].reset(); }); - }; + } function filterEvents(listEvents) { switch (filterOption) { @@ -127,14 +126,15 @@ .addClass("events"); var fragment = document.createDocumentFragment(); + if (changeType === "sort") { sortedList = sortEvents(ListOfEvents); } - var filterList = filterEvents(sortedList); - - var length = filterList.length(); + var filterList = filterEvents(sortedList), + length = filterList.length(), + i; - for (var i = 0; i < length; i++) + for (i = 0; i < length; i++) { var element = filterList.items[i]; var $el = addLiElement(element); @@ -155,35 +155,34 @@ */ function addLiElement (element) { - var $el = $('
        • ', { - className: 'event_item' - }); + var $el = $('
        • ') + .addClass("event_item"), - var $name = $('
          ', { + $name = $('
          ', { text: "Название: " + element.name - }).appendTo($el); + }).appendTo($el), - var $start = $('
          ', { + $start = $('
          ', { text: "Начало: " + element.start - }).appendTo($el); + }).appendTo($el), - var $end = $('
          ', { + $end = $('
          ', { text: "Окончание: " + element.end - }).appendTo($el); + }).appendTo($el), - var $location = $('
          ', { + $location = $('
          ', { text: "Местоположение: " + element.location - }).appendTo($el); + }).appendTo($el), - var $remindTime = $('
          ', { + $remindTime = $('
          ', { text: "Напомнить за: " + element.remindTime + "минут" - }).appendTo($el); + }).appendTo($el), - var $description = $('
          ', { + $description = $('
          ', { text: "Описание: " + element.description - }).appendTo($el); + }).appendTo($el), - var $raiting = $('
          ', { + $raiting = $('
          ', { text: "Рейтинг: " + element.raiting }).appendTo($el); From 17e0e5fa8627a1ce056ea8f2e7368f06105c62de Mon Sep 17 00:00:00 2001 From: yunnii Date: Sun, 25 Nov 2012 22:49:43 +0600 Subject: [PATCH 10/12] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/dz-7-jquery.iml | 9 ++++++ .idea/encodings.xml | 5 ++++ .idea/misc.xml | 11 +++++++ .idea/modules.xml | 9 ++++++ .idea/vcs.xml | 7 +++++ datepicker.js | 6 ---- documentAction.js | 62 +++++++++++++++------------------------ index.html | 15 +++++----- modernizr.custom.89360.js | 4 --- validation.js | 13 ++------ 10 files changed, 74 insertions(+), 67 deletions(-) create mode 100644 .idea/dz-7-jquery.iml create mode 100644 .idea/encodings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml delete mode 100644 datepicker.js delete mode 100644 modernizr.custom.89360.js diff --git a/.idea/dz-7-jquery.iml b/.idea/dz-7-jquery.iml new file mode 100644 index 0000000..6b8184f --- /dev/null +++ b/.idea/dz-7-jquery.iml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..e206d70 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f82faeb --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,11 @@ + + + + + + http://www.w3.org/1999/xhtml + + + + diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..455d32e --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..c80f219 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/datepicker.js b/datepicker.js deleted file mode 100644 index 6d819a7..0000000 --- a/datepicker.js +++ /dev/null @@ -1,6 +0,0 @@ -Modernizr.load({ - test: Modernizr.inputtypes.date, - nope: function () { - $("input[type='date']").datepicker(); - } -}); \ No newline at end of file diff --git a/documentAction.js b/documentAction.js index 4b80fba..837f887 100644 --- a/documentAction.js +++ b/documentAction.js @@ -6,7 +6,7 @@ filterOption = "all", sortOption = "without"; - $(document.body).on('load', initialise()); + $(document).ready(initialise); /** * Загружает свое состояние с сервера @@ -15,26 +15,20 @@ */ function initialise() { - $.ajax({ - dataType: 'json', - url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', - success: function (jqXHR) { + $( '.date' ).datepicker(); + + $.getJSON('current-event.json') + .complete(function () { $("#notify").hide(); }) + .error(function () { $('#notifyError').show(); }) + .success(function (result) { var i, newEvent; - for (i = 0; i < jqXHR.length; i++) { - newEvent = new Event(jqXHR[i]).validate(); + for (i = 0; i < result.length; i++) { + newEvent = new Event(result[i]).validate(); ListOfEvents = ListOfEvents.add(newEvent); } changeDocument("sort"); addListener(); - }, - error: function () { - $('#notifyError').show(); - return; - } - }) - .always(function () { - $("#notify").hide(); }); } /** @@ -68,18 +62,14 @@ var result = ListOfEvents.add(element); - $.ajax({ - type: 'POST', - url: 'http://yunnii.github.com/dz-7-jquery/current-event.json', - data: result.serialise(), - error: function () { + $.post('current-event.json', result.serialise()) + .error( function () { /*if (error === "error") { alert("Не могу подключиться к северу. Попробуйте позже"); return; }*/ - } - }) - .always(function () { + }) + .complete(function () { ListOfEvents = result; changeDocument("sort"); document.forms["form"].reset(); @@ -97,7 +87,7 @@ } } - function sortEvents(listEvents) { + function sortEvents() { switch (sortOption) { case "byName": return ListOfEvents.sortByName(); @@ -128,7 +118,7 @@ var fragment = document.createDocumentFragment(); if (changeType === "sort") { - sortedList = sortEvents(ListOfEvents); + sortedList = sortEvents(); } var filterList = filterEvents(sortedList), length = filterList.length(), @@ -193,42 +183,36 @@ * Навешивает обработчики событий на страницу */ function addListener() { - var $name = $("#title"); - var $start = $("#from"); - var $remindTime = $("#remindTime"); - var $filters = $('.filter'); - var $sort = $('.sort'); - var $button = $("#addButton"); - - $name.on('blur', function($event) { + + $("#title").on('blur', function($event) { var cur = $event.currentTarget; validateTitle(cur.value, $('#title_help')); }); - $start.on('blur', function ($event) { + $("#from").on('blur', function ($event) { var cur = $event.currentTarget; validateDate(cur.value, $('#from_help')); }); - $remindTime.on('blur', function ($event) { + $("#remindTime").on('blur', function ($event) { var cur = $event.currentTarget; - validateNumber(remindTime.value, $('#remindTime_help')); + validateNumber(cur.value, $('#remindTime_help')); }); - $filters.each(function(index) { + $('.filter').each(function(index) { $(this).on('change', function ($event) { filterOption = $('input[name="filter"]:checked').val(); changeDocument("filter"); })}); - $sort.each(function(index) { + $('.sort').each(function(index) { $(this).on('change', function ($event) { sortOption = $('input[name="sort"]:checked').val(); changeDocument("sort"); })}); - $button.on('click', preventDefault); + $("#addButton").on('click', preventDefault); } }(window)); \ No newline at end of file diff --git a/index.html b/index.html index a9b3120..3d27b7c 100644 --- a/index.html +++ b/index.html @@ -4,14 +4,15 @@ Календарь событий +
          Название:
          -
          С:
          -
          По:
          +
          С:
          +
          По:
          Место:
          Важность события: