Skip to content
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
80 changes: 80 additions & 0 deletions Calendar.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Календарь</title>
<link rel="stylesheet" type="text/css" href="choose.css">
<script type="text/javascript" src="http://yandex.st/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.tmpl.js"></script>
<script type="text/javascript" src="es5-shim.js"></script>
<script type="text/javascript" src="json2.js"></script>
<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 class="filterCollection">
<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 class = "Create_Event">

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

/**
* @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);
};

Collection.prototype.serialise = function () {// сериализует данные коллекции в JSON
"use strict";
return JSON.stringify(this.items);
};

Collection.prototype.sendCurrentState = function (item) {
"use strict";
var data = this.serialise();

// POST запрос
$.post('current-event.json', data);
};
97 changes: 97 additions & 0 deletions CreateCalendar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*jslint plusplus: true, browser: true, devel: true */
var currentEvents = new Events();

$.get('current-event.json', null, function (data, textStatus, jqXHR) {
"use strict";
if (textStatus === "success") {
var newEvents = JSON.parse(jqXHR.responseText),
newEvent,
n = newEvents.length,
i;
currentEvents.check = false;
for (i = 0; i < n; i++) {
newEvent = new Event(newEvents[i]);
currentEvents.add(newEvent);
}
WriteCalendar();
currentEvents.check = true;
}
});

function WriteCalendar() {
"use strict";
var filterEvents = currentEvents,
filter1,
filter2,
$sort,
bool,
sortBy,
res;

filter1 = $(".filter1").prop("checked");
filter2 = $(".filter2").prop("checked");
bool = false; // флажок. если =true, выдаем отфильтрованную коллекцию. иначе - всю.
if (filter1 === true) {
filterEvents = currentEvents.findFutureEvents();
bool = !bool;
}
if (filter2 === true) {
filterEvents = currentEvents.findPastEvents();
bool = !bool;
}

sortBy = "";
$sort = $(".filterCollection").find('[name="sort"]');
$sort.each(function (index, element) {
if ($(element).prop("checked") === true) {
sortBy = $(element).val();
}
});

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

function CreateCalendar() {
"use strict";
var date = $(".start_date").val(),// строка даты
time = $(".start_time").val(), // строка времени
startEv = date + "T" + time + ":00",
endEv,
element;

date = $(".end_date").val();
time = $(".end_time").val();
endEv = date + "T" + time + ":00";
element = new Event({
start: startEv,
end: endEv,
name: $(".New_Event").val(),
place: $(".plase_event").val(),
rating: parseFloat($(".rating_event").val().charAt(0)),
comment: $(".comment_event").val(),
link: $(".link_event").val()
});
element.validate();
currentEvents.add(element);

WriteCalendar();
}
$(document).ready(function () {
"use strict";
var $button = $(".add_event"),
$filter = $(".filterCollection").find('[name="filter"]'),
$sort = $(".filterCollection").find('[name="sort"]'),
i;
$button.click(CreateCalendar);
$filter.each(function (index, element) {
$(element).change(WriteCalendar);
});
$sort.each(function (index, element) {
$(element).change(WriteCalendar);
});
});
70 changes: 70 additions & 0 deletions Event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*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");
}
};

$.template("eventTemplate", "<p>Событие: ${Name}</p><p>Начало: ${Start}</p><p>Конец: ${End}</p><p>Продолжительность: ${Length}</p><p>Рейтинг: ${Rating}</p><p>Место: ${Place}</p><p>Комментарий: ${Comment}</p><p>Сcылка: ${Link}</p><br>");

Event.prototype.createSection = function () {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проблема этой функции в том, что каждый раз при вызове она будет генерировать новый шаблон, а не реиспользовать старый

$.template("eventTemplate", "<p>Событие: ${Name}</p><p>Начало: ${Start}</p><p>Конец: ${End}</p><p>Продолжительность: ${Length}</p><p>Рейтинг: ${Rating}</p><p>Место: ${Place}</p><p>Комментарий: ${Comment}</p><p>Сcылка: ${Link}</p><br>");

Event.prototype.createSection = function () {
    $.tmpl("eventTemplate", event_temp).appendTo(el);
}

"use strict";
var $el,
event_temp = [{Name: this.name, Start: this.start, End: this.end, Length: hours(this.end - this.start), Rating: this.rating, Place: this.place, Comment: this.comment, Link: this.link}];
$el = $('<section/>');
$.tmpl("eventTemplate", event_temp).appendTo($el);
return $el;
};
Loading