Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Дз5 #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions 5/Calendar.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Календарь</title>
<link rel="stylesheet" type="text/css" href="choose.css">
<script type="text/javascript" src="Model.js"></script>
<script type="text/javascript" src="Collection.js"></script>
<script type="text/javascript" src="Event.js"></script>
<script type="text/javascript" src="Events.js"></script>
<script type="text/javascript" src="CreateCalendar.js"></script>
</head>

<body>
<div>
<h3>Фильтрация текущей коллекции </h3>
<div>
<label><input type="checkbox" name="filter" class="filter1"/>Выбрать последущие события</label>
<label><input type="checkbox" name="filter" class="filter2"/>Выбрать предыдущие события</label>
<div>Сортировать по</div>
<label><input type="radio" name = "sort" value = "start"/>Началу</label>
<label><input type="radio" name = "sort" value = "length"/>Длительности</label>
<label><input type="radio" name = "sort" value = "rating"/>Рейтингу</label>
</div>
</div>
<hr/>
<form name = "Создание события">

<label>Название события
<input type="text" value="Новое событие" name = "New_Event" autofocus/>
</label>
<br>
<label>Дата начала:
<input type="date" name = "start_date"/>
</label>
<br>
<label>Время начала:
<input type="time" name = "start_time" />
</label>
<br>
<label>Дата окончания:
<input type="date" name = "end_date" />
</label>
<br>
<label>Время окончания:
<input type="time" name = "end_time" />
</label>
<br>
<label>Рейтинг
<select name = "rating_event">
<option>1 *</option>
<option>2 *</option>
<option>3 *</option>
<option>4 *</option>
<option>5 *</option>
</select>
</label>
<br>
<label>Место
<input type="text" name = "plase_event"/>
</label>
<br>
<label>Комментарий
<textarea name = "comment_event"></textarea>
</label>
<br>
<label>Ссылка
<input type="url" name = "link_event"/>
</label>
<br>
<input name="add_event" type="button" value="Добавить событие"/>
</form>
<hr/>
<h3> Текущее состояние коллекции </h3>
<script type="text/javascript">addListener()</script>
</body>
67 changes: 67 additions & 0 deletions 5/Collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*jslint plusplus: true, browser: true, devel: true */
// абстрактная коллекция Collection, представляющая из себя набор объектов Model
/**
* @constructor
* @param {Object} items
**/
var Collection = function (items) {
"use strict";
this.items = [];
var keyName;
for (keyName in items) {
if (items.hasOwnProperty(keyName)) {
this.items.push(items[keyName]);
}
}
};

/**
* @param {Model} model
*
* @return {Collection}
*/
Collection.prototype.add = function (model) {
"use strict";
this.items.push(model);
};

/**
* @param {Function} selector
*
* @example
* new Collection().filter(function (item) {
* return item.get('attendee').indexOf("me") !== -1;
* });
* @return {Collection}
*/
Collection.prototype.filter = function (selector) {
"use strict";
return new Collection(this.items.filter(selector));
};
/**
* @param {String} fieldName параметр, по которому происходит сотрировка
* @return {Collection}
*/
Collection.prototype.sortBy = function (fieldName) {
"use strict";
var items;
if (fieldName === "start") { // сортировка по началу события
items = this.items.sort(function (Event1, Event2) {
return Event1.start - Event2.start;
});
}
if (fieldName === "length") {//сортировка по длине события
items = this.items.sort(function (Event1, Event2) {
return (Event1.end - Event1.start) - (Event2.end - Event2.start);
});
}
if (fieldName === "rating") {//сортировка по рейтингу события
items = this.items.sort(function (Event1, Event2) {
return Event1.rating - Event2.rating;
}).reverse();
}
if (fieldName === "") {
items = this.items;
}
return new Collection(items);
};
77 changes: 77 additions & 0 deletions 5/CreateCalendar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*jslint plusplus: true, browser: true, devel: true */
var currentEvents = new Events();
function WriteCalendar() {
"use strict";
var filterEvents = currentEvents,
filter1,
filter2,
bool,
s,
res;

filter1 = document.querySelector('input[class="filter1"]:checked');
filter2 = document.querySelector('input[class="filter2"]:checked');
bool = false; // флажок. если =true, выдаем отфильтрованную коллекцию. иначе - всю.
if (filter1 !== null && filter1.value === "on") {
filterEvents = currentEvents.findFutureEvents();
bool = !bool;
}
if (filter2 !== null && filter2.value === "on") {
filterEvents = currentEvents.findPastEvents();
bool = !bool;
}

s = "";
if (document.querySelector('input[name="sort"]:checked') !== null) {
s = document.querySelector('input[name="sort"]:checked').value;
}

if (bool) {
res = new Events(filterEvents.sortBy(s).items);
} else {
res = new Events(currentEvents.sortBy(s).items);
}
res.write();
}

function CreateCalendar() {
"use strict";
var s = (document.getElementsByName("start_date")[0]).value,// строка даты
st = (document.getElementsByName("start_time")[0]).value, // строка времени
startEv = s + " " + st + ":00",
endEv,
element;

s = (document.getElementsByName("end_date")[0]).value;
st = (document.getElementsByName("end_time")[0]).value;
endEv = s + " " + st + ":00";

element = new Event({
start: new Date(startEv),
end: new Date(endEv),
name: (document.getElementsByName("New_Event")[0]).value,
place: (document.getElementsByName("plase_event")[0]).value,
rating: parseFloat((document.getElementsByName("rating_event")[0]).value[0]),
comment: (document.getElementsByName("comment_event")[0]).value,
link: (document.getElementsByName("link_event")[0]).value
});
element.validate();
currentEvents.add(element);

WriteCalendar();
}

var addListener = function () {
"use strict";
var button = document.getElementsByName("add_event")[0],
filter = document.getElementsByName("filter"),
sort = document.getElementsByName("sort"),
i;
button.addEventListener('click', CreateCalendar);
for (i = 0; i < filter.length; i++) {
filter[i].addEventListener('change', WriteCalendar);
}
for (i = 0; i < sort.length; i++) {
sort[i].addEventListener('change', WriteCalendar);
}
};
104 changes: 104 additions & 0 deletions 5/Event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*jslint plusplus: true, browser: true, devel: true */

function datatype(data) {// возвращает true, если data имеет тип дата и она корректна
"use strict";
if (typeof data === 'undefined') {
return false;
}
if (!data.getTime) {
return false;
}
if ('Invalid Date' === data) {
return false;
}
return true;
}

function ratingtype(rating) {// возвращает true, если rating - число от 0 до 5
"use strict";
if (typeof rating !== 'number') {
return false;
}
if (rating > 5 || rating < 0) {
return false;
}
return true;
}

function inherits(Constructor, SuperConstructor) {
"use strict";
var F = function () {};

F.prototype = SuperConstructor.prototype;

Constructor.prototype = new F();
}


// наследуем от Абстракнтого конструктора Model объект Event
var Event = function (data) {
"use strict";
Model.apply(this, arguments);
};
inherits(Event, Model);

Event.prototype.validate = function () {//проверяет корректность переданных данных.
"use strict";
if (!datatype(this.start)) {
throw new Error(this.start + " не является датой!");
}
if (!datatype(this.end)) {
throw new Error(this.end + " не является датой!");
}
if (this.start.getTime() - this.end.getTime() > 0) {
throw new Error("некорректное событие: не может закончиться раньше, чем начаться!!!");
}
if (!ratingtype(this.rating)) {
throw new Error("введите рейтинг от 0 до 5");
}
};

Event.prototype.createSection = function () {
"use strict";
var el, line, clone1, clone2, clone3, clone4, clone5, clone6, clone7;
el = document.createElement('section');
line = document.createElement('p');
line.textContent = "Событие: " + this.name;
el.appendChild(line);

clone1 = line.cloneNode(true);
clone1.textContent = "Начало: " + this.start;
el.appendChild(clone1);

clone2 = line.cloneNode(true);
clone2.textContent = "Конец: " + this.end;
el.appendChild(clone2);

clone3 = line.cloneNode(true);
clone3.textContent = "Продолжительность: " + hours(this.end - this.start);
el.appendChild(clone3);

clone4 = line.cloneNode(true);
clone4.textContent = "Рейтинг: " + this.rating;
el.appendChild(clone4);

if (this.place !== '') {
clone5 = line.cloneNode(true);
clone5.textContent = "Место: " + this.place;
el.appendChild(clone5);
}

if (this.comment !== '') {
clone6 = line.cloneNode(true);
clone6.textContent = "Комментарий: " + this.comment;
el.appendChild(clone6);
}

if (this.link !== '') {
clone7 = line.cloneNode(true);
clone7.textContent = "Ссылка: " + this.link;
el.appendChild(clone7);
}
el.appendChild(document.createElement('br'));
return el;
};
Loading