omi v1.2.1 - support install method when using the Object.createStore method

This commit is contained in:
dntzhang 2017-03-30 16:07:14 +08:00
parent 09f3bead65
commit e205158ed6
12 changed files with 467 additions and 308 deletions

View File

@ -66,10 +66,10 @@ $ npm install omi
## CDN
* [https://unpkg.com/omi@1.2.0/dist/omi.min.js](https://unpkg.com/omi@1.2.0/dist/omi.min.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.js](https://unpkg.com/omi@1.2.0/dist/omi.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.lite.min.js](https://unpkg.com/omi@1.2.0/dist/omi.lite.min.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.lite.js](https://unpkg.com/omi@1.2.0/dist/omi.lite.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.min.js](https://unpkg.com/omi@1.2.1/dist/omi.min.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.js](https://unpkg.com/omi@1.2.1/dist/omi.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.lite.min.js](https://unpkg.com/omi@1.2.1/dist/omi.lite.min.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.lite.js](https://unpkg.com/omi@1.2.1/dist/omi.lite.js)
## 感谢
@ -130,10 +130,10 @@ if using 'omi.lite.js' (without [mustache.js](https://github.com/janl/mustache.j
## CDN
* [https://unpkg.com/omi@1.2.0/dist/omi.min.js](https://unpkg.com/omi@1.2.0/dist/omi.min.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.js](https://unpkg.com/omi@1.2.0/dist/omi.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.lite.min.js](https://unpkg.com/omi@1.2.0/dist/omi.lite.min.js)
* [https://unpkg.com/omi@1.2.0/dist/omi.lite.js](https://unpkg.com/omi@1.2.0/dist/omi.lite.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.min.js](https://unpkg.com/omi@1.2.1/dist/omi.min.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.js](https://unpkg.com/omi@1.2.1/dist/omi.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.lite.min.js](https://unpkg.com/omi@1.2.1/dist/omi.lite.min.js)
* [https://unpkg.com/omi@1.2.1/dist/omi.lite.js](https://unpkg.com/omi@1.2.1/dist/omi.lite.js)
## Thanks

3
dist/omi.js vendored
View File

@ -1,5 +1,5 @@
/*!
* Omi v1.2.0 By dntzhang
* Omi v1.2.1 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
@ -279,6 +279,7 @@ return /******/ (function(modules) { // webpackBootstrap
function Obj(data, isReady) {
_classCallCheck(this, Obj);
this.data = data;
option.methods.install && option.methods.install.call(this);
return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady));
}

3
dist/omi.lite.js vendored
View File

@ -1,5 +1,5 @@
/*!
* Omi v1.2.0 By dntzhang
* Omi v1.2.1 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
@ -278,6 +278,7 @@ return /******/ (function(modules) { // webpackBootstrap
function Obj(data, isReady) {
_classCallCheck(this, Obj);
this.data = data;
option.methods.install && option.methods.install.call(this);
return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady));
}

File diff suppressed because one or more lines are too long

4
dist/omi.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{
"name": "omi",
"version": "1.2.0",
"version": "1.2.1",
"description": "Open and modern framework for building user interfaces.",
"main": "dist/omi.js",
"scripts": {

View File

@ -68,44 +68,104 @@ return /******/ (function(modules) { // webpackBootstrap
;(function () {
var OmiRouter = {};
var OmiRouter = {}
var Omi = true
? __webpack_require__(1)
: window.Omi;
var parser = __webpack_require__(2);
: window.Omi
var parser = __webpack_require__(2),
renderTo = null,
params = { },
Component = null,
store = null,
routerOption = { },
preRenderTo = null,
preInstance = null
OmiRouter.init = function (option) {
routerOption = option
option.routes.forEach(function (route) {
route.reg = parser(route.path)
})
Omi.extendPlugin('omi-router', function (dom, instance) {
dom.setAttribute('href', '##')
dom.setAttribute('href', 'javascript:void(0)')
dom.addEventListener('click', function () {
var to = dom.getAttribute('to')
option.routes.every(function (route) {
var arr = to.match(route.reg);
if (arr) {
Omi.render(new route.component(), option.renderTo, {
store: {data: arr}
})
return false
}
return true
})
hashMapping(dom.getAttribute('to'))
}, false)
})
}
function getParams(toArr, pathArr) {
var params = {}
toArr.forEach(function (item, index) {
if (index > 0) {
params[pathArr[index].replace(':','')] = item
}
})
return params
}
function hashMapping(to) {
routerOption.routes.every(function (route) {
var toArr = to.match(route.reg);
if (toArr) {
var pathArr = route.path.match(route.reg)
params = getParams(toArr, pathArr)
renderTo = route.renderTo || routerOption.renderTo
store = route.store || routerOption.store
Component = route.component
pushState(to)
return false
}
return true
})
}
function pushState(route){
window.location.hash = route
}
window.addEventListener('hashchange', function() {
hashMapping(window.location.hash.replace('#',''), renderTo)
if(store){
store.$route = { }
store.$route.params = params
}else{
store = {
methods:{
install:function(){
this.$route = { }
this.$route.params = params
}
}
}
}
if(preRenderTo === renderTo&&preInstance){
deleteInstance(preInstance)
}
var instance = new Component()
Omi.render(instance, renderTo, {
store: store
})
preInstance = instance
preRenderTo = renderTo
}, false)
function deleteInstance(instance){
for(var key in Omi.instances){
if(Omi.instances.hasOwnProperty(key)){
Omi.instances[key].id = instance.id
delete Omi.instances[key]
instance = null
break
}
}
}
OmiRouter.destroy = function () {
delete Omi.plugins['omi-finger']
delete Omi.plugins['omi-router']
}
if (true) {
@ -118,12 +178,7 @@ return /******/ (function(modules) { // webpackBootstrap
window.OmiRouter = OmiRouter
}
})()
//<2F>ı<EFBFBD>url
//֧<>ֺ<EFBFBD><D6BA><EFBFBD>
//dist<73><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
})()
/***/ },
/* 1 */

View File

@ -3,4 +3,4 @@
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("omi")):"function"==typeof define&&define.amd?define(["omi"],t):"object"==typeof exports?exports.OmiRouter=t(require("omi")):e.OmiRouter=t(e.omi)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){!function(){var t={},n=r(1),o=r(2);t.init=function(e){e.routes.forEach(function(e){e.reg=o(e.path)}),n.extendPlugin("omi-router",function(t,r){t.setAttribute("href","##"),t.addEventListener("click",function(){var r=t.getAttribute("to");e.routes.every(function(t){var o=r.match(t.reg);return!o||(n.render(new t.component,e.renderTo,{store:{data:o}}),!1)})},!1)})},t.destroy=function(){delete n.plugins["omi-finger"]},e.exports=t}()},function(t,r){t.exports=e},function(e,t,r){function n(e,t){for(var r,n=[],o=0,i=0,u="",p=t&&t.delimiter||"/";null!=(r=v.exec(e));){var f=r[0],l=r[1],s=r.index;if(u+=e.slice(i,s),i=s+f.length,l)u+=l[1];else{var d=e[i],g=r[2],x=r[3],h=r[4],m=r[5],y=r[6],E=r[7];u&&(n.push(u),u="");var w=null!=g&&null!=d&&d!==g,b="+"===y||"*"===y,R="?"===y||"*"===y,j=r[2]||p,A=h||m;n.push({name:x||o++,prefix:g||"",delimiter:j,optional:R,repeat:b,partial:w,asterisk:!!E,pattern:A?c(A):E?".*":"[^"+a(j)+"]+?"})}}return i<e.length&&(u+=e.substr(i)),u&&n.push(u),n}function o(e,t){return p(n(e,t))}function i(e){return encodeURI(e).replace(/[\/?#]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}function u(e){return encodeURI(e).replace(/[?#]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}function p(e){for(var t=new Array(e.length),r=0;r<e.length;r++)"object"==typeof e[r]&&(t[r]=new RegExp("^(?:"+e[r].pattern+")$"));return function(r,n){for(var o="",p=r||{},a=n||{},c=a.pretty?i:encodeURIComponent,f=0;f<e.length;f++){var l=e[f];if("string"!=typeof l){var s,d=p[l.name];if(null==d){if(l.optional){l.partial&&(o+=l.prefix);continue}throw new TypeError('Expected "'+l.name+'" to be defined')}if(m(d)){if(!l.repeat)throw new TypeError('Expected "'+l.name+'" to not repeat, but received `'+JSON.stringify(d)+"`");if(0===d.length){if(l.optional)continue;throw new TypeError('Expected "'+l.name+'" to not be empty')}for(var g=0;g<d.length;g++){if(s=c(d[g]),!t[f].test(s))throw new TypeError('Expected all "'+l.name+'" to match "'+l.pattern+'", but received `'+JSON.stringify(s)+"`");o+=(0===g?l.prefix:l.delimiter)+s}}else{if(s=l.asterisk?u(d):c(d),!t[f].test(s))throw new TypeError('Expected "'+l.name+'" to match "'+l.pattern+'", but received "'+s+'"');o+=l.prefix+s}}else o+=l}return o}}function a(e){return e.replace(/([.+*?=^!:${}()[\]|\/\\])/g,"\\$1")}function c(e){return e.replace(/([=!:$\/()])/g,"\\$1")}function f(e,t){return e.keys=t,e}function l(e){return e.sensitive?"":"i"}function s(e,t){var r=e.source.match(/\((?!\?)/g);if(r)for(var n=0;n<r.length;n++)t.push({name:n,prefix:null,delimiter:null,optional:!1,repeat:!1,partial:!1,asterisk:!1,pattern:null});return f(e,t)}function d(e,t,r){for(var n=[],o=0;o<e.length;o++)n.push(h(e[o],t,r).source);var i=new RegExp("(?:"+n.join("|")+")",l(r));return f(i,t)}function g(e,t,r){return x(n(e,r),t,r)}function x(e,t,r){m(t)||(r=t||r,t=[]),r=r||{};for(var n=r.strict,o=r.end!==!1,i="",u=0;u<e.length;u++){var p=e[u];if("string"==typeof p)i+=a(p);else{var c=a(p.prefix),s="(?:"+p.pattern+")";t.push(p),p.repeat&&(s+="(?:"+c+s+")*"),s=p.optional?p.partial?c+"("+s+")?":"(?:"+c+"("+s+"))?":c+"("+s+")",i+=s}}var d=a(r.delimiter||"/"),g=i.slice(-d.length)===d;return n||(i=(g?i.slice(0,-d.length):i)+"(?:"+d+"(?=$))?"),i+=o?"$":n&&g?"":"(?="+d+"|$)",f(new RegExp("^"+i,l(r)),t)}function h(e,t,r){return m(t)||(r=t||r,t=[]),r=r||{},e instanceof RegExp?s(e,t):m(e)?d(e,t,r):g(e,t,r)}var m=r(3);e.exports=h,e.exports.parse=n,e.exports.compile=o,e.exports.tokensToFunction=p,e.exports.tokensToRegExp=x;var v=new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"),"g")},function(e,t){e.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}}])});
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("omi")):"function"==typeof define&&define.amd?define(["omi"],t):"object"==typeof exports?exports.OmiRouter=t(require("omi")):e.OmiRouter=t(e.omi)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){!function(){function t(e,t){var r={};return e.forEach(function(e,n){n>0&&(r[t[n].replace(":","")]=e)}),r}function n(e){d.routes.every(function(r){var n=e.match(r.reg);if(n){var i=r.path.match(r.reg);return f=t(n,i),p=r.renderTo||d.renderTo,l=r.store||d.store,s=r.component,o(e),!1}return!0})}function o(e){window.location.hash=e}function i(e){for(var t in u.instances)if(u.instances.hasOwnProperty(t)){u.instances[t].id=e.id,delete u.instances[t],e=null;break}}var a={},u=r(1),c=r(2),p=null,f={},s=null,l=null,d={},h=null,g=null;a.init=function(e){d=e,e.routes.forEach(function(e){e.reg=c(e.path)}),u.extendPlugin("omi-router",function(e,t){e.setAttribute("href","javascript:void(0)"),e.addEventListener("click",function(){n(e.getAttribute("to"))},!1)})},window.addEventListener("hashchange",function(){n(window.location.hash.replace("#",""),p),l?(l.$route={},l.$route.params=f):l={methods:{install:function(){this.$route={},this.$route.params=f}}},h===p&&g&&i(g);var e=new s;u.render(e,p,{store:l}),g=e,h=p},!1),a.destroy=function(){delete u.plugins["omi-router"]},e.exports=a}()},function(t,r){t.exports=e},function(e,t,r){function n(e,t){for(var r,n=[],o=0,i=0,a="",u=t&&t.delimiter||"/";null!=(r=v.exec(e));){var f=r[0],s=r[1],l=r.index;if(a+=e.slice(i,l),i=l+f.length,s)a+=s[1];else{var d=e[i],h=r[2],g=r[3],m=r[4],x=r[5],y=r[6],w=r[7];a&&(n.push(a),a="");var E=null!=h&&null!=d&&d!==h,b="+"===y||"*"===y,$="?"===y||"*"===y,R=r[2]||u,j=m||x;n.push({name:g||o++,prefix:h||"",delimiter:R,optional:$,repeat:b,partial:E,asterisk:!!w,pattern:j?p(j):w?".*":"[^"+c(R)+"]+?"})}}return i<e.length&&(a+=e.substr(i)),a&&n.push(a),n}function o(e,t){return u(n(e,t))}function i(e){return encodeURI(e).replace(/[\/?#]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}function a(e){return encodeURI(e).replace(/[?#]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}function u(e){for(var t=new Array(e.length),r=0;r<e.length;r++)"object"==typeof e[r]&&(t[r]=new RegExp("^(?:"+e[r].pattern+")$"));return function(r,n){for(var o="",u=r||{},c=n||{},p=c.pretty?i:encodeURIComponent,f=0;f<e.length;f++){var s=e[f];if("string"!=typeof s){var l,d=u[s.name];if(null==d){if(s.optional){s.partial&&(o+=s.prefix);continue}throw new TypeError('Expected "'+s.name+'" to be defined')}if(x(d)){if(!s.repeat)throw new TypeError('Expected "'+s.name+'" to not repeat, but received `'+JSON.stringify(d)+"`");if(0===d.length){if(s.optional)continue;throw new TypeError('Expected "'+s.name+'" to not be empty')}for(var h=0;h<d.length;h++){if(l=p(d[h]),!t[f].test(l))throw new TypeError('Expected all "'+s.name+'" to match "'+s.pattern+'", but received `'+JSON.stringify(l)+"`");o+=(0===h?s.prefix:s.delimiter)+l}}else{if(l=s.asterisk?a(d):p(d),!t[f].test(l))throw new TypeError('Expected "'+s.name+'" to match "'+s.pattern+'", but received "'+l+'"');o+=s.prefix+l}}else o+=s}return o}}function c(e){return e.replace(/([.+*?=^!:${}()[\]|\/\\])/g,"\\$1")}function p(e){return e.replace(/([=!:$\/()])/g,"\\$1")}function f(e,t){return e.keys=t,e}function s(e){return e.sensitive?"":"i"}function l(e,t){var r=e.source.match(/\((?!\?)/g);if(r)for(var n=0;n<r.length;n++)t.push({name:n,prefix:null,delimiter:null,optional:!1,repeat:!1,partial:!1,asterisk:!1,pattern:null});return f(e,t)}function d(e,t,r){for(var n=[],o=0;o<e.length;o++)n.push(m(e[o],t,r).source);var i=new RegExp("(?:"+n.join("|")+")",s(r));return f(i,t)}function h(e,t,r){return g(n(e,r),t,r)}function g(e,t,r){x(t)||(r=t||r,t=[]),r=r||{};for(var n=r.strict,o=r.end!==!1,i="",a=0;a<e.length;a++){var u=e[a];if("string"==typeof u)i+=c(u);else{var p=c(u.prefix),l="(?:"+u.pattern+")";t.push(u),u.repeat&&(l+="(?:"+p+l+")*"),l=u.optional?u.partial?p+"("+l+")?":"(?:"+p+"("+l+"))?":p+"("+l+")",i+=l}}var d=c(r.delimiter||"/"),h=i.slice(-d.length)===d;return n||(i=(h?i.slice(0,-d.length):i)+"(?:"+d+"(?=$))?"),i+=o?"$":n&&h?"":"(?="+d+"|$)",f(new RegExp("^"+i,s(r)),t)}function m(e,t,r){return x(t)||(r=t||r,t=[]),r=r||{},e instanceof RegExp?l(e,t):x(e)?d(e,t,r):h(e,t,r)}var x=r(3);e.exports=m,e.exports.parse=n,e.exports.compile=o,e.exports.tokensToFunction=u,e.exports.tokensToRegExp=g;var v=new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"),"g")},function(e,t){e.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}}])});

View File

@ -125,8 +125,8 @@
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*!
* Omi v1.1.5 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* Omi v1.2.0 By dntzhang
* Github: https://github.com/AlloyTeam/omi
* MIT Licensed.
*/
(function webpackUniversalModuleDefinition(root, factory) {
@ -238,6 +238,8 @@
Omi.STYLEPREFIX = "omi_style_";
Omi.STYLESCOPEDPREFIX = "omi_scoped_";
Omi.style = {};
Omi.componentConstructor = {};
//fix ie bug
@ -264,14 +266,14 @@
};
}
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
(function () {
'use strict';
@ -405,6 +407,7 @@
function Obj(data, isReady) {
_classCallCheck(this, Obj);
this.data = data;
option.methods.install && option.methods.install.call(this);
return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady));
}
@ -568,9 +571,9 @@
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/
/*global define: false Mustache: true*/
@ -595,9 +598,9 @@
return typeof object === 'function';
}
/**
* More correct typeof string handling array
* which normally returns typeof 'object'
/**
* More correct typeof string handling array
* which normally returns typeof 'object'
*/
function typeStr(obj) {
return isArray(obj) ? 'array' : typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
@ -607,9 +610,9 @@
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}
/**
* Null safe way of checking whether or not an object,
* including its prototype, has a given property
/**
* Null safe way of checking whether or not an object,
* including its prototype, has a given property
*/
function hasProperty(obj, propName) {
return obj != null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && propName in obj;
@ -650,27 +653,27 @@
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*/
function parseTemplate(template, tags) {
if (!template) return [];
@ -790,9 +793,9 @@
return nestTokens(squashTokens(tokens));
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/
function squashTokens(tokens) {
var squashedTokens = [];
@ -815,11 +818,11 @@
return squashedTokens;
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/
function nestTokens(tokens) {
var nestedTokens = [];
@ -850,9 +853,9 @@
return nestedTokens;
}
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
*/
function Scanner(string) {
this.string = string;
@ -860,16 +863,16 @@
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
/**
* Returns `true` if the tail is empty (end of string).
*/
Scanner.prototype.eos = function eos() {
return this.tail === '';
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/
Scanner.prototype.scan = function scan(re) {
var match = this.tail.match(re);
@ -884,9 +887,9 @@
return string;
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function scanUntil(re) {
var index = this.tail.search(re),
@ -910,9 +913,9 @@
return match;
};
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
*/
function Context(view, parentContext) {
this.view = view;
@ -920,17 +923,17 @@
this.parent = parentContext;
}
/**
* Creates a new context using the given view with this context
* as the parent.
/**
* Creates a new context using the given view with this context
* as the parent.
*/
Context.prototype.push = function push(view) {
return new Context(view, this);
};
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
*/
Context.prototype.lookup = function lookup(name) {
var cache = this.cache;
@ -950,16 +953,16 @@
names = name.split('.');
index = 0;
/**
* Using the dot notion path in `name`, we descend through the
* nested objects.
*
* To be certain that the lookup has been successful, we have to
* check if the last object in the path actually has the property
* we are looking for. We store the result in `lookupHit`.
*
* This is specially necessary for when the value has been set to
* `undefined` and we want to avoid looking up parent contexts.
/**
* Using the dot notion path in `name`, we descend through the
* nested objects.
*
* To be certain that the lookup has been successful, we have to
* check if the last object in the path actually has the property
* we are looking for. We store the result in `lookupHit`.
*
* This is specially necessary for when the value has been set to
* `undefined` and we want to avoid looking up parent contexts.
**/
while (value != null && index < names.length) {
if (index === names.length - 1) lookupHit = hasProperty(value, names[index]);
@ -984,25 +987,25 @@
return value;
};
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
*/
function Writer() {
this.cache = {};
}
/**
* Clears all cached templates in this writer.
/**
* Clears all cached templates in this writer.
*/
Writer.prototype.clearCache = function clearCache() {
this.cache = {};
};
/**
* Parses and caches the given `template` and returns the array of tokens
* that is generated from the parse.
/**
* Parses and caches the given `template` and returns the array of tokens
* that is generated from the parse.
*/
Writer.prototype.parse = function parse(template, tags) {
var cache = this.cache;
@ -1013,14 +1016,14 @@
return tokens;
};
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
*/
Writer.prototype.render = function render(template, view, partials) {
var tokens = this.parse(template);
@ -1028,14 +1031,14 @@
return this.renderTokens(tokens, context, partials, template);
};
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
*/
Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate) {
var buffer = '';
@ -1122,25 +1125,25 @@
// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();
/**
* Clears all cached templates in the default writer.
/**
* Clears all cached templates in the default writer.
*/
mustache.clearCache = function clearCache() {
return defaultWriter.clearCache();
};
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
*/
mustache.parse = function parse(template, tags) {
return defaultWriter.parse(template, tags);
};
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer.
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer.
*/
mustache.render = function render(template, view, partials) {
if (typeof template !== 'string') {
@ -1236,8 +1239,10 @@
ignoreStoreData: false,
preventSelfUpdate: false,
selfDataFirst: false,
domDiffDisabled: false
domDiffDisabled: false,
scopedSelfCSS: false
}, option);
this._omi_scopedSelfCSS = componentOption.scopedSelfCSS;
this._omi_preventSelfUpdate = componentOption.preventSelfUpdate;
this._omi_domDiffDisabled = componentOption.domDiffDisabled;
this._omi_ignoreStoreData = componentOption.ignoreStoreData;
@ -1656,15 +1661,19 @@
key: '_generateHTMLCSS',
value: function _generateHTMLCSS() {
this.CSS = (this.style() || '').replace(/<\/?style>/g, '');
var shareAttr = this.___omi_constructor_name ? _omi2['default'].STYLESCOPEDPREFIX + this.___omi_constructor_name.toLowerCase() : this._omi_scoped_attr;
if (this.CSS) {
this.CSS = _style2['default'].scoper(this.CSS, "[" + this._omi_scoped_attr + "]");
if (this.CSS !== this._preCSS && !this._omi_server_rendering) {
_style2['default'].addStyle(this.CSS, this.id);
this._preCSS = this.CSS;
if (this._omi_scopedSelfCSS || !_omi2['default'].style[shareAttr]) {
this.CSS = _style2['default'].scoper(this.CSS, this._omi_scopedSelfCSS ? "[" + this._omi_scoped_attr + "]" : "[" + shareAttr + "]");
_omi2['default'].style[shareAttr] = this.CSS;
if (this.CSS !== this._preCSS && !this._omi_server_rendering) {
_style2['default'].addStyle(this.CSS, this.id);
this._preCSS = this.CSS;
}
}
}
var tpl = this.render();
this.HTML = this._scopedAttr(_omi2['default'].template(tpl ? tpl : "", this.data), this._omi_scoped_attr).trim();
this.HTML = this._scopedAttr(_omi2['default'].template(tpl ? tpl : "", this.data), this._omi_scoped_attr, shareAttr).trim();
if (this._omi_server_rendering) {
this.HTML = '\r\n<style id="' + _omi2['default'].STYLEPREFIX + this.id + '">\r\n' + this.CSS + '\r\n</style>\r\n' + this.HTML;
this.HTML += '\r\n<input type="hidden" data-omi-id="' + this.id + '" class="' + _omi2['default'].STYLESCOPEDPREFIX + '_hidden_data" value=\'' + JSON.stringify(this.data) + '\' />\r\n';
@ -1672,16 +1681,22 @@
}
}, {
key: '_scopedAttr',
value: function _scopedAttr(html, id) {
value: function _scopedAttr(html, id, shareAtrr) {
var _this9 = this;
return html.replace(/<[^/]([A-Za-z]*)[^>]*>/g, function (m) {
var str = m.split(" ")[0].replace(">", "");
return m.replace(str, str + " " + id);
if (_this9._omi_scopedSelfCSS || !_this9.___omi_constructor_name) {
return m.replace(str, str + " " + id);
} else {
return m.replace(str, str + " " + id + " " + shareAtrr);
}
});
}
}, {
key: '_getDataset',
value: function _getDataset(childStr) {
var _this9 = this;
var _this10 = this;
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
@ -1689,20 +1704,20 @@
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key.indexOf('on') === 0) {
var handler = _this9.parent[value];
var handler = _this10.parent[value];
if (handler) {
baseData[key] = handler.bind(_this9.parent);
baseData[key] = handler.bind(_this10.parent);
}
} else if (key.indexOf('data-') === 0) {
_this9._dataset[_this9._capitalize(key.replace('data-', ''))] = value;
_this10._dataset[_this10._capitalize(key.replace('data-', ''))] = value;
} else if (key.indexOf(':data-') === 0) {
_this9._dataset[_this9._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')');
_this10._dataset[_this10._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')');
} else if (key === ':data') {
_this9._dataset = eval('(' + value + ')');
_this10._dataset = eval('(' + value + ')');
} else if (key === 'data') {
_this9._dataset = _this9._extractPropertyFromString(value, _this9.parent);
_this10._dataset = _this10._extractPropertyFromString(value, _this10.parent);
} else if (key === 'group-data') {
_this9._dataset = _this9._extractPropertyFromString(value, _this9.parent)[_this9._omi_groupDataIndex];
_this10._dataset = _this10._extractPropertyFromString(value, _this10.parent)[_this10._omi_groupDataIndex];
}
});
@ -1731,30 +1746,6 @@
}, {
key: '_extractChildrenString',
value: function _extractChildrenString(child) {
var _this10 = this;
if (_omi2['default'].customTags.length === 0) return;
child.HTML = this._replaceTags(_omi2['default'].customTags, child.HTML);
var arr = child.HTML.match(/<child[^>][\s\S]*?tag=['|"](\S*)['|"][\s\S]*?><\/child>/g);
if (arr) {
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this10.children[i];
if (cmi && cmi.___omi_constructor_name === name) {
cmi._omiChildStr = childStr;
}
});
}
}
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
var _this11 = this;
if (_omi2['default'].customTags.length === 0) return;
@ -1770,9 +1761,46 @@
var name = attr.tag;
delete attr.tag;
var cmi = _this11.children[i];
if (cmi && cmi.___omi_constructor_name === name) {
cmi._omiChildStr = childStr;
}
});
}
}
}, {
key: '_extractChildren',
value: function _extractChildren(child) {
var _this12 = this;
if (_omi2['default'].customTags.length === 0) return;
child.HTML = this._replaceTags(_omi2['default'].customTags, child.HTML);
var arr = child.HTML.match(/<child[^>][\s\S]*?tag=['|"](\S*)['|"][\s\S]*?><\/child>/g);
child._omiGroupDataCounter = {};
if (arr) {
arr.forEach(function (childStr, i) {
var json = (0, _html2json2['default'])(childStr);
var attr = json.child[0].attr;
var name = attr.tag;
delete attr.tag;
var cmi = _this12.children[i];
//if not first time to invoke _extractChildren method
if (cmi && cmi.___omi_constructor_name === name) {
cmi._omiChildStr = childStr;
Object.keys(attr).forEach(function (key) {
var value = attr[key];
if (key === 'group-data') {
if (child._omiGroupDataCounter.hasOwnProperty(value)) {
child._omiGroupDataCounter[value]++;
} else {
child._omiGroupDataCounter[value] = 0;
}
cmi._omi_groupDataIndex = child._omiGroupDataCounter[value];
}
});
cmi._childRender(childStr);
} else {
(function () {
@ -1802,15 +1830,15 @@
child._omiGroupDataCounter[value] = 0;
}
groupDataIndex = child._omiGroupDataCounter[value];
dataset = _this11._extractPropertyFromString(value, child)[groupDataIndex];
dataset = _this12._extractPropertyFromString(value, child)[groupDataIndex];
} else if (key.indexOf('data-') === 0) {
dataset[_this11._capitalize(key.replace('data-', ''))] = value;
dataset[_this12._capitalize(key.replace('data-', ''))] = value;
} else if (key.indexOf(':data-') === 0) {
dataset[_this11._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')');
dataset[_this12._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')');
} else if (key === ':data') {
dataset = eval('(' + value + ')');
} else if (key === 'data') {
dataset = _this11._extractPropertyFromString(value, child);
dataset = _this12._extractPropertyFromString(value, child);
} else if (key === 'preventSelfUpdate' || key === 'psu') {
_omi_option.preventSelfUpdate = true;
} else if (key === 'selfDataFirst' || key === 'sdf') {
@ -1819,6 +1847,8 @@
_omi_option.domDiffDisabled = true;
} else if (key === 'ignoreStoreData' || key === 'isd') {
_omi_option.ignoreStoreData = true;
} else if (key === 'scopedSelfCSS' || key === 'ssc') {
_omi_option.scopedSelfCSS = true;
}
});
@ -1892,7 +1922,7 @@
g2 = "";
}
if (g0.indexOf(';base64') > 0) {
if (g0.indexOf(';base64') !== -1 || g0.indexOf('/') !== -1) {
return g0;
}
@ -2019,15 +2049,15 @@
return fragment.childNodes[0];
}
/**
* Returns true if two node's names are the same.
*
* NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same
* nodeName and different namespace URIs.
*
* @param {Element} a
* @param {Element} b The target element
* @return {boolean}
/**
* Returns true if two node's names are the same.
*
* NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same
* nodeName and different namespace URIs.
*
* @param {Element} a
* @param {Element} b The target element
* @return {boolean}
*/
function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
@ -2048,21 +2078,21 @@
}
}
/**
* Create an element, optionally with a known namespace URI.
*
* @param {string} name the element name, e.g. 'div' or 'svg'
* @param {string} [namespaceURI] the element's namespace URI, i.e. the value of
* its `xmlns` attribute or its inferred namespace.
*
* @return {Element}
/**
* Create an element, optionally with a known namespace URI.
*
* @param {string} name the element name, e.g. 'div' or 'svg'
* @param {string} [namespaceURI] the element's namespace URI, i.e. the value of
* its `xmlns` attribute or its inferred namespace.
*
* @return {Element}
*/
function createElementNS(name, namespaceURI) {
return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name);
}
/**
* Copies the children of one DOM element to another DOM element
/**
* Copies the children of one DOM element to another DOM element
*/
function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
@ -2142,18 +2172,18 @@
}
var specialElHandlers = {
/**
* Needed for IE. Apparently IE doesn't think that "selected" is an
* attribute when reading over the attributes using selectEl.attributes
/**
* Needed for IE. Apparently IE doesn't think that "selected" is an
* attribute when reading over the attributes using selectEl.attributes
*/
OPTION: function OPTION(fromEl, toEl) {
syncBooleanAttrProp(fromEl, toEl, 'selected');
},
/**
* The "value" attribute is special for the <input> element since it sets
* the initial value. Changing the "value" attribute without changing the
* "value" property will have no effect since it is only used to the set the
* initial value. Similar for the "checked" attribute, and "disabled".
/**
* The "value" attribute is special for the <input> element since it sets
* the initial value. Changing the "value" attribute without changing the
* "value" property will have no effect since it is only used to the set the
* initial value. Similar for the "checked" attribute, and "disabled".
*/
INPUT: function INPUT(fromEl, toEl) {
syncBooleanAttrProp(fromEl, toEl, 'checked');
@ -2281,13 +2311,13 @@
}
}
/**
* Removes a DOM node out of the original DOM
*
* @param {Node} node The node to remove
* @param {Node} parentNode The nodes parent
* @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded.
* @return {undefined}
/**
* Removes a DOM node out of the original DOM
*
* @param {Node} node The node to remove
* @param {Node} parentNode The nodes parent
* @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded.
* @return {undefined}
*/
function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
@ -2674,16 +2704,16 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
/*
* html2json for omi
* https://github.com/AlloyTeam/omi
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
* Original code by Jxck
* https://github.com/Jxck/html2json
/*
* html2json for omi
* https://github.com/AlloyTeam/omi
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
* Original code by Jxck
* https://github.com/Jxck/html2json
*/
// Regular Expressions for parsing tags and attributes
@ -2995,7 +3025,8 @@
}, {
key: "update",
value: function update() {
this._mergeInstances(this.instances);
this._mergeInstances();
this._mergeSelfInstances();
this.instances.forEach(function (instance) {
return instance.update();
});
@ -3004,21 +3035,34 @@
});
}
}, {
key: "_mergeInstances",
value: function _mergeInstances(instances) {
key: "_mergeSelfInstances",
value: function _mergeSelfInstances() {
var _this = this;
var arr = [];
var idArr = [];
instances.forEach(function (instance) {
idArr.push(instance.id);
this.updateSelfInstances.forEach(function (instance) {
if (!_this._checkSelfUpdateInstance(instance)) {
arr.push(instance);
}
});
this.updateSelfInstances = arr;
}
}, {
key: "_mergeInstances",
value: function _mergeInstances() {
var _this2 = this;
var arr = [];
this.idArr = [];
this.instances.forEach(function (instance) {
_this2.idArr.push(instance.id);
});
instances.forEach(function (instance) {
this.instances.forEach(function (instance) {
if (!instance.parent) {
arr.push(instance);
} else {
if (!_this._isSubInstance(instance, idArr)) {
if (!_this2._isSubInstance(instance)) {
arr.push(instance);
}
}
@ -3026,13 +3070,22 @@
this.instances = arr;
}
}, {
key: "_checkSelfUpdateInstance",
value: function _checkSelfUpdateInstance(instance) {
if (this.idArr.indexOf(instance.id) !== -1) {
return true;
} else if (instance.parent) {
return this._checkSelfUpdateInstance(instance.parent);
}
}
}, {
key: "_isSubInstance",
value: function _isSubInstance(instance, arr) {
if (arr.indexOf(instance.parent.id) !== -1) {
value: function _isSubInstance(instance) {
if (this.idArr.indexOf(instance.parent.id) !== -1) {
return true;
} else if (instance.parent.parent) {
return this._isSubInstance(instance.parent, arr);
return this._isSubInstance(instance.parent);
}
}
}]);
@ -3088,14 +3141,16 @@
var Omi = true ? __webpack_require__(1) : window.Omi;
var parser = __webpack_require__(4),
routes = null,
renderTo = null,
params = {},
Component = null;
Component = null,
store = null,
routerOption = {},
preRenderTo = null,
preInstance = null;
OmiRouter.init = function (option) {
routes = option.routes;
renderTo = option.renderTo;
routerOption = option;
option.routes.forEach(function (route) {
route.reg = parser(route.path);
});
@ -3104,20 +3159,7 @@
dom.setAttribute('href', 'javascript:void(0)');
dom.addEventListener('click', function () {
var to = dom.getAttribute('to');
option.routes.every(function (route) {
var toArr = to.match(route.reg);
if (toArr) {
var pathArr = route.path.match(route.reg);
params = getParams(toArr, pathArr);
renderTo = option.renderTo;
Component = route.component;
pushState(to);
return false;
}
return true;
});
hashMapping(dom.getAttribute('to'));
}, false);
});
};
@ -3133,11 +3175,15 @@
}
function hashMapping(to) {
routes.every(function (route) {
var arr = to.match(route.reg);
if (arr) {
pushState(to);
routerOption.routes.every(function (route) {
var toArr = to.match(route.reg);
if (toArr) {
var pathArr = route.path.match(route.reg);
params = getParams(toArr, pathArr);
renderTo = route.renderTo || routerOption.renderTo;
store = route.store || routerOption.store;
Component = route.component;
pushState(to);
return false;
}
return true;
@ -3150,11 +3196,41 @@
window.addEventListener('hashchange', function () {
hashMapping(window.location.hash.replace('#', ''), renderTo);
Omi.render(new Component(), renderTo, {
store: { data: params }
if (store) {
store.$route = {};
store.$route.params = params;
} else {
store = {
methods: {
install: function install() {
this.$route = {};
this.$route.params = params;
}
}
};
}
if (preRenderTo === renderTo && preInstance) {
deleteInstance(preInstance);
}
var instance = new Component();
Omi.render(instance, renderTo, {
store: store
});
preInstance = instance;
preRenderTo = renderTo;
}, false);
function deleteInstance(instance) {
for (var key in Omi.instances) {
if (Omi.instances.hasOwnProperty(key)) {
Omi.instances[key].id = instance.id;
delete Omi.instances[key];
instance = null;
break;
}
}
}
OmiRouter.destroy = function () {
delete Omi.plugins['omi-router'];
};
@ -3744,8 +3820,9 @@
_createClass(User, [{
key: 'beforeRender',
value: function beforeRender() {
this.data.name = this.$store.data.name;
this.data.category = this.$store.data.category;
var params = this.$store.$route.params;
this.data.name = params.name;
this.data.category = params.category;
this.info = this.queryInfo(this.data.name);
this.data.age = this.info.age;
this.data.sex = this.info.sex;

View File

@ -3,8 +3,9 @@
class User extends Omi.Component {
beforeRender(){
this.data.name = this.$store.data.name
this.data.category = this.$store.data.category
let params = this.$store.$route.params
this.data.name = params.name
this.data.category = params.category
this.info = this.queryInfo(this.data.name)
this.data.age = this.info.age
this.data.sex = this.info.sex

View File

@ -13,14 +13,16 @@
: window.Omi
var parser = require('path-to-regexp'),
routes = null,
renderTo = null,
params = { },
Component = null
Component = null,
store = null,
routerOption = { },
preRenderTo = null,
preInstance = null
OmiRouter.init = function (option) {
routes = option.routes
renderTo = option.renderTo
routerOption = option
option.routes.forEach(function (route) {
route.reg = parser(route.path)
})
@ -29,20 +31,7 @@
dom.setAttribute('href', 'javascript:void(0)')
dom.addEventListener('click', function () {
var to = dom.getAttribute('to')
option.routes.every(function (route) {
var toArr = to.match(route.reg);
if (toArr) {
var pathArr = route.path.match(route.reg)
params = getParams(toArr, pathArr)
renderTo = option.renderTo
Component = route.component
pushState(to)
return false
}
return true
})
hashMapping(dom.getAttribute('to'))
}, false)
})
}
@ -58,11 +47,15 @@
}
function hashMapping(to) {
routes.every(function (route) {
var arr = to.match(route.reg);
if (arr) {
pushState(to)
routerOption.routes.every(function (route) {
var toArr = to.match(route.reg);
if (toArr) {
var pathArr = route.path.match(route.reg)
params = getParams(toArr, pathArr)
renderTo = route.renderTo || routerOption.renderTo
store = route.store || routerOption.store
Component = route.component
pushState(to)
return false
}
return true
@ -75,10 +68,40 @@
window.addEventListener('hashchange', function() {
hashMapping(window.location.hash.replace('#',''), renderTo)
Omi.render(new Component(), renderTo, {
store: {data: params}
if(store){
store.$route = { }
store.$route.params = params
}else{
store = {
methods:{
install:function(){
this.$route = { }
this.$route.params = params
}
}
}
}
if(preRenderTo === renderTo&&preInstance){
deleteInstance(preInstance)
}
var instance = new Component()
Omi.render(instance, renderTo, {
store: store
})
}, false);
preInstance = instance
preRenderTo = renderTo
}, false)
function deleteInstance(instance){
for(var key in Omi.instances){
if(Omi.instances.hasOwnProperty(key)){
Omi.instances[key].id = instance.id
delete Omi.instances[key]
instance = null
break
}
}
}
OmiRouter.destroy = function () {
delete Omi.plugins['omi-router']

View File

@ -155,6 +155,7 @@ Omi.createStore = function(option) {
function Obj(data, isReady) {
_classCallCheck(this, Obj)
this.data = data
option.methods.install && option.methods.install.call(this)
return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady))
}