Skip to content
Closed
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
2 changes: 1 addition & 1 deletion .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"jquery": true,
"node": true,
"globals": {
"no": false,
"no": true,
"ns": true,
"DocumentTouch": false,
"Vow": false,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"engines": {
"node": "*"
},
"main": "src/index.js",
"files": [
"css",
"dist",
Expand Down
19 changes: 19 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
var ns = require('./ns.js');

require('./ns.log.js');
require('./ns.dom.js');
require('./ns.consts.js');
require('./ns.consts.events.js');
require('./ns.object.js');
require('./ns.router.js');
require('./ns.layout.js');
require('./ns.model.js');
require('./ns.modelCollection.js');
require('./ns.box.js');
require('./ns.view.js');
require('./ns.viewCollection.js');
require('./ns.page.js');
require('./ns.request.js');
require('./ns.update.js');

module.exports = ns;
3 changes: 3 additions & 0 deletions src/ns.box.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

/**
* Это внутренний класс, который не должен использоваться приложением.
* @classdesc Box - это тип View, который умеет выбирать какие View показывать.
Expand Down
2 changes: 2 additions & 0 deletions src/ns.consts.events.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var ns = ns || require('./ns.js');

/**
* Хеш событий для удобного биндинга touch/desktop
* @type {object}
Expand Down
2 changes: 2 additions & 0 deletions src/ns.consts.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var ns = ns || require('./ns.js');

/**
* Типы узлов ns.layout
* @enum {string}
Expand Down
2 changes: 2 additions & 0 deletions src/ns.dom.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var ns = ns || require('./ns.js');

/**
* Replaces oldNode with newNode
* @param {Element} oldNode
Expand Down
19 changes: 10 additions & 9 deletions src/ns.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var no = no || require('nommon');

/**
* noscript MVC framework
* @namespace
Expand All @@ -6,7 +8,7 @@
*/
var ns = {};

if (typeof window === 'undefined') {
if (no.de) {
Copy link
Contributor

Choose a reason for hiding this comment

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

откуда в ns завязка на descript? А если я не хочу descript, а хочу express ?

Copy link
Member Author

Choose a reason for hiding this comment

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

no.de надо читать как node, а не как no.descript.
Это свойство из nommon.
Зависимости от descript - нет )

Copy link

Choose a reason for hiding this comment

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

no.de - так не правильно определять что мы находимся в nodejs.

Если вы будете использовать browserify, то сразу наткнетесь на ошибку.
Лучше использовать такую прверку

Copy link
Contributor

Choose a reason for hiding this comment

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

А ещё лучше - вообще не использовать проверки и писать код, не зависящий от окружения.
Вот не знаю, утопия это в наших обстоятельствах, или нет

Copy link
Member Author

Choose a reason for hiding this comment

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

@maksimr при желании, и эта проверка не будет работать, если в браузере нужный json-чик забацать )
Но и window можно и в nodejs объявить )
В общем - мы все умрём )

Copy link

Choose a reason for hiding this comment

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

@edoroshenko +1

@chestozo Я написал потому, что столкнулся с проблемами при созаднии yate-playground :)

module.exports = ns;
}

Expand All @@ -20,7 +22,7 @@ ns.events = no.extend( {}, no.Events );
* @const
* @type {Boolean}
*/
ns.IS_TOUCH = Boolean(
ns.IS_TOUCH = !no.de && Boolean(
'ontouchstart' in window ||
(window.DocumentTouch && document instanceof DocumentTouch)
);
Expand Down Expand Up @@ -70,15 +72,14 @@ ns.parseQuery = function(s) {
};

/**
* Performs json templating.
* @param {*} json
* @param {string} mode
* @param {string} [module='main']
* @returns {Element}
* Генерация HTML по json дереву видов.
* @param {object} json Дерево видов.
* @param {string} mode Начальная мода: выполнить матчинг для шаблона с этой модой.
* @param {string} [module='main'] id Модуля yate.
* @returns {string} Отрендеренный HTML код.
*/
ns.tmpl = function(json, mode, module) {
var result = yr.run(module || 'main', json, mode);
return ns.html2node(result);
return yr.run(module || 'main', json, mode);
};

/**
Expand Down
4 changes: 3 additions & 1 deletion src/ns.layout.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');
Copy link
Member

Choose a reason for hiding this comment

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

Может начать собирать Noscript через Browserify? Тогда каждый файл будет отдельным CommonJS модулем и, как следствие, (1) не придется оборачивать каждый файл в IIFE, (2) не придется помнить, что в выражении var ns = ns || require('ns'); первая часть для браузера, а вторая для сервера.

Copy link
Member Author

Choose a reason for hiding this comment

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

А напиши пример, пожалуйста.
К примеру, как будет выглядеть такой вот файл в терминах Browserify:

var ns = ns || require('ns');
ns.coolMethod = function() {
    return 'cool';
};

Copy link
Member

Choose a reason for hiding this comment

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

Вообще, в случае вспомогательной функции или класса, можно не прикреплять его к неймспейсу в самом модуле (чтобы без побочных эффектов):

// cool-method.js
var COOL = 'cool';
module.exports = function coolMethod() {
    return COOL;
};

// ns.js
var ns = {};
ns.coolMethod = require('./cool-method');
module.exports = ns;

Но если без сильных изменений, то можно записать так:

var ns = require('./ns');

module.exports = ns.coolMethod = function() {
    return 'cool';
};

Copy link
Member Author

Choose a reason for hiding this comment

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

Хм хм хм )
Ну может быть и стоит сделать как ты предлагаешь.
/сс @doochik @edoroshenko ?

Copy link
Contributor

Choose a reason for hiding this comment

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

Я за.
И уж точно не стоит писать везде no || require('nommon')

Copy link
Contributor

Choose a reason for hiding this comment

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

да, browserify решает эту проблему

Еще вот такая запись var no = no || require('nommon') не даст нам исполнять код в браузере или сделать модуль, потому что получится вот так

(function() {
  // и тут всегда будет вызываться require, потому что no определен локально
 var no = no || require('nommon');
})()

Copy link
Member Author

Choose a reason for hiding this comment

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

Ну не надо это делать внутри замыкания просто
https://github.com/yandex-ui/noscript/blob/server.render.92/src/ns.view.js#L1-L2

Copy link
Contributor

Choose a reason for hiding this comment

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

Мы сами оборачиваем эти файлы в модули и такие строки все сломают


(function() {

/**
Expand Down Expand Up @@ -189,5 +192,4 @@
}
return key;
}

})();
6 changes: 4 additions & 2 deletions src/ns.log.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
(function(ns) {
var ns = ns || require('./ns.js');

(function() {

/**
* Модуль логирования ошибок.
Expand Down Expand Up @@ -44,4 +46,4 @@
/* jshint unused: false */
};

})(ns);
})();
3 changes: 3 additions & 0 deletions src/ns.model.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

(function() {

/**
Expand Down
3 changes: 3 additions & 0 deletions src/ns.modelCollection.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

(function() {

/**
Expand Down
2 changes: 2 additions & 0 deletions src/ns.object.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var ns = ns || require('./ns.js');

/**
* Хелперы для работы с объектами
* @namespace
Expand Down
3 changes: 3 additions & 0 deletions src/ns.page.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

(function() {

/**
Expand Down
5 changes: 4 additions & 1 deletion src/ns.request.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

(function() {

/**
Expand Down Expand Up @@ -42,7 +45,7 @@
ns.request.models = function(models, options) {

// Загрузка порционных данных. В этом случае грузим не саму модель, а порцию данных.
models = $.map(models, function(model) {
models = models.map(function(model) {
return model.getRequest ? model.getRequest() : model;
});

Expand Down
3 changes: 3 additions & 0 deletions src/ns.router.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

/**
* Find best page for url.
* @namespace
Expand Down
116 changes: 68 additions & 48 deletions src/ns.update.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,32 @@
var no = no || require('nommon');
var ns = ns || require('./ns.js');

(function() {

/**
* Создает ns.Update
* Id последнего созданного update-а.
* @type {number}
*/
var update_id = -1;

/**
* Current ns.Updates.
* @type ns.Update[]
* @private
*/
var currentUpdates = [];

/**
* Создает ns.Update.
*
* @classdesc ns.Update
* @param {ns.View} view Корневой view.
* @param {object} layout Layout для этого view, результат от ns.layout.page()
* @param {object} params Параметры, результат от ns.router()
* @param {object} [options] Options for ns.Update
* @param {ns.U.EXEC} [options.execFlag=ns.U.EXEC.GLOBAL] Options for ns.Update
* @param {object} layout Layout для этого view, результат от ns.layout.page().
* @param {object} params Параметры, результат от ns.router().
* @param {object} [options] Опции для ns.Update.
* @param {ns.U.EXEC} [options.execFlag=ns.U.EXEC.GLOBAL] Тип ns.Update (GLOBAL, PARALLEL, ASYNC).
* @param {boolean} [options.syncOnly=] Флаг "запросить данные только для синхронных видов". Нужен для генерации html на сервере.
* @param {boolean} [options.renderOnly=] Флаг "нужен только HTML код". Нужен для генерации html на сервере.
* @constructor
* @example
* ```js
Expand Down Expand Up @@ -39,28 +58,15 @@

this.id = ++update_id;

options = options || {};
this.options = options = options || {};

/**
* Execution flag
* @type {ns.U.EXEC}
*/
this.EXEC_FLAG = options.execFlag || ns.U.EXEC.GLOBAL;
this.execFlag = options.execFlag || ns.U.EXEC.GLOBAL;
};

/**
* Current ns.Updates.
* @type ns.Update[]
* @private
*/
var currentUpdates = [];

/**
* Id последнего созданного update-а.
* @type {number}
*/
var update_id = -1;

/**
* @see ns.U.STATUS
* @type {ns.U.STATUS}
Expand Down Expand Up @@ -131,11 +137,15 @@
return;
}

that._update(async);
// resolve main promise and return promises for async views
that.done({
async: asyncUpdaterPromises
});
if (that.options.renderOnly) {
that.done(that._render());
} else {
that._update(async);
// resolve main promise and return promises for async views
that.done({
async: asyncUpdaterPromises
});
}
}, function(models) {
// NOTE here we do not even try to handle the error. Or we should do it?
that.error({
Expand All @@ -150,6 +160,10 @@
});
});

if (this.options.syncOnly) {
return resultPromise;
}

// Для каждого async-view запрашиваем его модели.
// Когда они приходят, запускаем точно такой же update.
// Причем ждем отрисовку sync-view, чтобы точно запуститься после него.
Expand Down Expand Up @@ -200,27 +214,13 @@
async_view: view,
models: result[1]
});
})
.fail(function(e) {
asyncUpdaterPromises[asyncViewId].reject({
error: e,
async_view: view,
models: models
});
});
});

return resultPromise;
};

/**
* Обновляет DOM и триггерит нужные события
* @param {boolean} [async=false] Флаг асинхронного updater'а.
* @private
*/
ns.Update.prototype._update = function(async) {
// TODO: Проверить, что не начался уже более новый апдейт.

ns.Update.prototype._render = function() {
var params = this.params;
var layout = this.layout;

Expand All @@ -231,12 +231,32 @@

ns.log.debug('[ns.Update]', 'start()', this.id, 'updateTree', tree);

var node;
// если пустое дерево, то ничего не реднерим,
// но кидаем события и скрываем/открываем блоки
var html;
if (!ns.object.isEmpty(tree.views)) {
node = this.render(tree, this.params, this.layout);
ns.log.debug('[ns.Update]', 'start()', this.id, 'new node', node.cloneNode(true));
html = this.render(tree, params, layout);
ns.log.debug('[ns.Update]', 'start()', this.id, 'rendered html', html);
}

return html;
};

/**
* Обновляет DOM и триггерит нужные события
* @param {boolean} [async=false] Флаг асинхронного updater'а.
* @private
*/
ns.Update.prototype._update = function(async) {
// TODO: Проверить, что не начался уже более новый апдейт.

var params = this.params;
var layout = this.layout;

var node;
var html = this._render();
if (html) {
node = ns.html2node(html);
}

var viewEvents = {
Expand Down Expand Up @@ -271,7 +291,7 @@
* @param {object} tree Дерево видов.
* @param {object} params Параметры страницы.
* @param {object} layout Раскладка страницы.
* @returns {HTMLElement}
* @returns {string}
*/
ns.Update.prototype.render = function(tree, params, layout) {
/* jshint unused: false */
Expand Down Expand Up @@ -353,7 +373,7 @@
var FLAG_PARALLEL = FLAGS.PARALLEL;
var FLAG_ASYNC = FLAGS.ASYNC;

var newRunExecutionFlag = newUpdate.EXEC_FLAG;
var newRunExecutionFlag = newUpdate.execFlag;
var i;
var j;

Expand All @@ -368,7 +388,7 @@
var run = currentRuns[i];

// don't terminated paraller updates
if (run.EXEC_FLAG === FLAG_PARALLEL) {
if (run.execFlag === FLAG_PARALLEL) {
survivedRuns.push(run);

} else {
Expand All @@ -382,7 +402,7 @@

// check whether we have one global update
for (i = 0, j = currentRuns.length; i < j; i++) {
if (currentRuns[i].EXEC_FLAG === FLAG_GLOBAL) {
if (currentRuns[i].execFlag === FLAG_GLOBAL) {
return false;
}
}
Expand All @@ -399,7 +419,7 @@
* @returns Boolean.
*/
ns.Update.prototype.isGlobal = function() {
return this.EXEC_FLAG === ns.U.EXEC.GLOBAL;
return this.execFlag === ns.U.EXEC.GLOBAL;
};

/**
Expand Down
Loading