blog
blog copied to clipboard
一些代码片段
从以前旧博客迁移至此 2016-04-30 01:51:05
发布订阅者模式
var Observer = function () {
};
Observer.prototype = {
constructor: Observer,
subscribe: function (eventName, func) {
if (!this[eventName]) this[eventName] = [];
this[eventName].push(func);
},
publish: function (eventName, data) {
var _this = this;
if (!this[eventName]) this[eventName] = [];
this[eventName].forEach(function (func) {
func.call(_this, data);
});
}
};
var ob = new Observer();
// 订阅
ob.subscribe('dialog', function (data) {
console.log('there are data:' + data);
});
// 发布
ob.publish('dialog', [1, 2, 3, 4]);
解析多层属性,类似angularJS的$parse服务
function parse(properties) {
const agm = properties.split('.');
return function(target, undefined) {
let result = null;
(function parseTarget(target, agm) {
if (target === void 0) {
console.error(
'Uncaught TypeError: Cannot read property ' + agm[0] + ' of undefined'
);
result = target;
return result;
}
if (agm.length <= 1) {
result = target[agm[0]];
return result;
}
target = target[agm[0]];
agm.shift();
parseTarget(target, agm);
})(target, agm);
return result;
};
}
const o = {
a: {
b: {
c: 233
}
}
};
console.log(parse('a.b.c')(o)); // 233