Last active
December 24, 2015 12:09
-
-
Save pavelpower/6795814 to your computer and use it in GitHub Desktop.
Вынес обсервер в отдельный класс, от которого уже наследуются классы использующие функциональность обсервера. Думаю такой пример будет вполне позновательным. :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ClassObserver = (function(){ | |
function constructor () {} | |
constructor.prototype = { | |
events: {}, | |
on: function(event, hendler, ctx) { | |
var array_handlers = this.events[event]; | |
array_handlers = array_handlers == null ? [] : array_handlers; | |
array_handlers.push({ handler: hendler, ctx: ctx || this }); | |
this.events[event] = array_handlers; | |
}, | |
trigger: function(event, ctx) { | |
var args = Array.prototype.splice.call(arguments, 1), | |
array_handlers = this.events[event], | |
handler_obj; | |
// проверить есть ли событие? | |
if (array_handlers == null) | |
return; | |
// есть - выполняем | |
for (var i = 0; i < array_handlers.length; i++) { | |
handler_obj = array_handlers[i]; | |
handler_obj.handler.apply(ctx || handler_obj.ctx, args); | |
} | |
} | |
}; | |
return constructor; | |
}()); | |
var ClassA = (function() { | |
// Class A | |
function constructor(name) { | |
this.name = name; | |
} | |
// prototype inherit Observer | |
constructor.prototype = new ClassObserver; | |
// extend | |
constructor.prototype.setName = function(value) { | |
var oldName = this.name; | |
this.trigger('before_change:name', value, this.name); | |
this.name = value; | |
this.trigger('change:name', value, oldName); | |
this.trigger('changed'); | |
}; | |
return constructor; | |
}()); | |
var ClassB = (function() { | |
// Class B | |
// Class B not inheriting Observer | |
function constructor(name) { | |
this.name = name; | |
} | |
// extend | |
constructor.prototype = { | |
setName : function(someValue, value) { | |
this.someName = someValue; | |
this.name = value; | |
} | |
}; | |
return constructor; | |
}()); | |
var a = new ClassA('Gosha'); | |
var b = new ClassB('Boris'); | |
// Change name b on old Name form a; | |
a.on('change:name', b.setName, b); | |
a.on('changed', function() { | |
console.log('Name after change:', a.name, b.name); | |
}); | |
a.on('before_change:name', function() { | |
console.log('Name before change:', a.name, b.name); | |
}); | |
// call change name | |
a.setName('Petya'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment