I am actually playing with Javascript doing a small game and I would like to implement what I've found on http://www.crockford.com/javascript/inheritance.html which is something similar to:
ZParenizor.method('toString', function () {
if (this.getValue()) {
return this.uber('toString');
}
return "-0-";
});
I can't find any reference the the library used to make such development possible. Any ideas? Otherwise, I'm looking for a good library that will aid my OOP developments.
Thank you
Edit:
I am looking for a OOP solution / library for Node.js. Please note that I'm new to Node.js
2 months later
Maybe you do need a library, ES5 is verbose as hell so I've created pd
Original answer
I am looking for a OOP solution / library for Node.js.
You don't need a library. You have ES5.
JavaScript does not have classical OOP. It has prototyping OOP.
This means you have only objects. The only thing you can do with objects is extend, manipulate and clone them.
Manipulate
var o = {};
o.foo = "bar";
Extend
var o = someObject;
Object.defineProperties(o, {
"foo": { value: "foo" },
"bar": { value: "bar" }
"method": { value: function () { } }
}
Clone
var o = someObject;
var p = Object.create(o);
Clone and extend
var o = someObject;
var p = Object.create(o, {
"foo": { value: "foo" },
"bar": { value: "bar" }
"method": { value: function () { } }
}
It's important to understand how Object.create, Object.defineProperty and Object.defineProperties work.
The cloning operation isn't actually cloning. It's creating a new object from a blueprint. A blueprint is an object. It places the blueprint in the [[Prototype]]. The [[Prototype]] lives in the .__proto__ property which I'll use for demonstration.
var o = {};
var p = Object.create(o);
p.__proto__ === o; // true
var q = Object.create(p);
q.__proto__.__proto__ === o;
var r = Object.create(q);
r.__proto__.__proto__.__proto__ === o;
Disclaimer: .__proto__ is deprecated. Don't use it in code. It has it's uses for debugging and sanity checks though.
The main point here is that accessing properties from o in r it has to walk 3 levels up the prototype chain and this gets expensive. To solve that problem, rather then cloning random objects you should clone specific blueprints (and you should have one blueprint per object).
// Parent blueprint
var Parent = (function _Parent() {
// create blank object
var self = Object.create({});
// object logic
return self;
}());
// factory function
var createParent = function _createParent(foo) {
// create a object with a Parent prototype
return Object.create(Parent, {
foo: { value: foo }
});
}
var Child = (function _Child() {
var self = Object.create(Parent);
// other stuff
return self;
}());
var createChild = function _createChild(bar) {
return Object.create(Child, {
bar: { value: bar }
})
};
Here's a snippet from some code I'm working on that you can use as an example:
var Sketchpad = (function _SketchPad() {
var self = Object.create({});
var mousemove = function _mousemove(e) {
this.drawLine(e);
};
self._init = function _init() {
this.$elem.bind({
"mousemove": mousemove.bind(this),
});
this.pens = {};
$("#clear").bind("click", this.clear.bind(this));
$("#undo").bind("click", (function _undoPath() {
this.pen.undo();
}).bind(this));
return this;
};
self.clear = function() {
this.paper.clear();
};
return self;
}());
createSketch = function _createSketchPad(id, w, h) {
var paper = Raphael(id, w, h);
var pen = createPen(paper);
var o = Object.create(Sketchpad, {
paper: { value: paper },
$elem: { value: $("#" + id) },
pen: {
get: function() { return pen; },
set: function(v) { pen = v; }
}
});
return o._init();
};
MooTools is one of the best libraries in terms of OOP Javascript.
You can create classes, interfaces, use inheritance, etc.
Documentation
http://mootools.net/docs/core
Tutorial - MooTools OOP
http://www.phpeveryday.com/articles/MooTools-Basic-Creating-Classes-MooTools-P919.html
You might also be interested in GNU ease.js. If you are not interested in the library itself, its manual goes extensively into the implementation details.
You could also see the author's paper on Classical OOP in ECMAScript.
You could try Joose, https://github.com/SamuraiJack/Task-Joose-NodeJS. Although, I'd personally recommend to stick with Javascript's object functionality as provided by ES5.
In the article you referenced, he was simply giving an example of what was possible with inheritance in javascript. He was not using a framework, but showing you how to extend your own classes you have written.
Frameworks for javascript include Backbone.js (mvc), and MooTools (oop).
extjs has support for OOP with Ext.define and Ext.extend (and Ext.ns). See this example on Sencha.com
Ext.extend is the older method, but is still sometimes useful. You would do something like this:
Ext.ns('myApp.myPackage'); // create a namespace
(function() { // this adds it to the namespace
var MyClass = Ext.extend(BaseClass, {
property: 1,
constructor: function(config) {
Ext.apply(this, config);
},
method: function(a, b) {
this.property = a + b;
}
});
myApp.myPackage.MyClass = MyClass;
}) ()
With Ext.define in Ext 4+ you can do:
Ext.define('myApp.myPackage.MyClass', // don't need to define the namespace first
extend: 'BaseClass' // notice the base class is referenced by a string,
requires: 'AnotherClass',
mixins: { mixin : 'MixinPackage' },
property: 1,
constructor: function(config) {
//...
}
method: function(a, b) {
this.property = a + b;
}
});
Note that you can also use traditional OOP in javascript with 'new' and function.prototype
If you want to do a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf.
It allows you to use OOP (and so the same classes) on both the server (node) and client (browser) sides.
It also provides a nice dependency injection mechanism (looking as the one of Symfony2 if you come from the PHP community).
Related
Today, I have an config for the translateProvider looking like this:
App.config(['$translateProvider', function ($translateProvider) {
$translateProvider.preferredLanguage('en-US');
$translateProvider.useLoader('TranslationLoader', { versionIdentifier : 127} );
$translateProvider.useMissingTranslationHandler('MissingTranslationHandler');
}]);
The problem is that I don't know the value of the formIdentifier-option at configuration time. I get this value after resolving the first state in ui-route. I've tried to set the translationProvides loader in the state's controller, but realized that that's not possible :)
Any ideas?
angular-translate allows you to use any service as a loader as long as it meets a desired interface. But it doesn't restrict you in ways of how you pass additional parameters to the loader. So, you may pass them just like you want.
For example, you can set additional parameters directly to the loader. Just implement setters for them on top of your loader:
module.factory('Loader', [
'$q',
function($q) {
var myParam;
var loader = function(options) {
var allParams = angular.extend({}, { myParam: myParam }, options);
var deferred = $q.defer();
// load stuff
return deferred.promise;
};
loader.setMyParam = function(param) {
myParam = param;
};
return loader;
}])
Also, you may try to set these parameters with some helper service (either sync or async:
module.factory('SyncLoader', [
'$q', '$injector',
function($q, $injector) {
var loader = function(options) {
var helper = $injector.get(options.helper);
var myParam = helper.getMyParam();
var deferred = $q.defer();
// load stuff
return deferred.promise;
};
return loader;
}]);
or
module.factory('AsyncLoader', [
'$q', '$injector',
function($q, $injector) {
var loader = function(options) {
var helper = $injector.get(options.helper);
var deferred = $q.defer();
helper.getMyParam()
.then(function success(myParam) {
// load stuff
}, function error() {
// fail, probably
});
return deferred.promise;
};
return loader;
}]);
Also, it might be possible to use events somehow. Or, maybe, there are some other ways possible. It depends on a specific architecture.
Is there a way to have a static variable in a dojo (1.8) module so that I can retain state?
Example, say I set some value in some/module
require([
'some/module'
], function (module) {
module.setSomeValue(3);
});
.. and then want to retrieve it later
define([
'some/module'
], function(module) {
return {
start: function() {
var x = module.getSomeValue();
}
};
});
A solution that works but seems like a hack,
acompany = window.acompany || {};
acompany.project = acompany.project || {
};
require([
], function() {
var debug = false;
acompany.project.module = {
/* static variables and functions here */
};
});
define([
], function () {
return acompany.project.module;
});
Actually there is always only single instance of AMD module, because (source):
define has two additional important characteristics that may not be immediately obvious:
Module creation is lazy and asynchronous, and does not occur immediately when define is called. This means that factory is not executed, and any dependencies of the module will not be resolved, until some running code actually requires the module.
Once a module value has been entered into the module namespace, it is not recomputed each time it is demanded. On a practical level, this means that factory is only invoked once, and the returned value is cached and shared among all code that uses a given module. (Note: the dojo loader includes the nonstandard function require.undef, which undefines a module value.)
In addition you do not have to provide just factory function, you can provide an object literal as well:
define("some/module", {
someValue: "some",
otherValue: "other"
});
Then somewhere else in your code:
require(["some/module"], function(module) {
console.log("module.someValue", module.someValue); // some
module.someValue = "some changed";
});
require(["some/module"], function(module) {
console.log("module.someValue", module.someValue); // some changed
});
More robust solution includes an instance of dojo/Stateful, so you can watch for changes and define custom setters and getters:
define("some/stateful-module", ["dojo/Stateful"], function(Stateful){
var stateful = new Stateful({
someValue: "some",
otherValue: "other"
});
return stateful;
});
Then somewhere else in your code:
require(["some/stateful-module"], function(module) {
console.log("stateful-module.someValue:", module.get("someValue"));
module.watch(function(name, oldValue, newValue) {
console.log("stateful-module: property"
, name
, "changed from"
, "'" + oldValue + "'"
, "to"
, "'" + newValue + "'"
);
});
});
require(["some/stateful-module"], function(module) {
module.set("someValue", "some changed");
});
See how it works at jsFiddle: http://jsfiddle.net/phusick/fHvZf/. It's in a single file there, but it will work the same way across the whole application unless you require.undef(mid) the module.
There are multiple files in Dojo like dojo/date/locale that define static variables and functions and not widgets/classes using dojo.declare.
Define the module
define([
'dojo/_base/lang/',
'some/module'
], function(lang, module) {
var m = lang.getObject('some.module', true);
m.x = 0;
m.doSomething = function(){
// doSomething
};
return m;
});
Use the module
require([
'some/module'
], function(someModule) {
var debug = false;
/* someModule - static variables and functions here */
if(someModule.x == 0){
}
});
I'm trying to figure out how ExtJS4 passes around config objects.
I want to do the equivalent of...
store = function(config){
if ( typeof config.call !== 'unndefined' ){
config.url = "server.php?c=" + config.call || config.url;
};
Sketch.Data.AutoSaveStore.superclass.constructor.call(this,config);
};
Ext.extend(store, Ext.data.Store{})
I am probably missing something obvious here, but having dug around in the sandbox file, the closest I have come is....
Ext.define('My.awesome.Class', {
// what i would like to pass.
config:{},
constructor: function(config) {
this.initConfig(config);
return this;
}
});
which doesn't seem to work if you do something like...
var awesome = Ext.create('My.awesome.Class',{
name="Super awesome"
});
alert(awesome.getName()); // 'awesome.getName is not a function'
However
Ext.define('My.awesome.Class', {
// The default config
config: {
name: 'Awesome',
isAwesome: true
},
constructor: function(config) {
this.initConfig(config);
return this;
}
});
var awesome = Ext.create('My.awesome.Class',{
name="Super awesome"
});
alert(awesome.getName()); // 'Super Awesome'
This is biting me in the rear end when trying to do complex store extensions.
Anyone have any idea how I pass a bunch of random params to the prototype?
You should not be using new operator to create new instance on your class. In ExtJS4, you should use Ext.create() method.
Try doing:
var awesome = Ext.create('My.awesome.Class');
alert(awesome.getName());
And if you want to pass some param when creating an instance, you can do the following
var awesome = Ext.create('My.awesome.Class',{name:'New Awesome'});
Given the following code:
JE.events = {
self: this,
controller: {
init: function(){
$(".monthheader").click(function () {
JE.events.model.get($(this).attr('title'));
return false;
});
return this;
}
},
model: {
get: function(monthnum){
...
}
}
}
How would i replace the call to
JE.events.model.get(..);
by something like
self.model.get(..);
The whole code is more or less in this gist https://gist.github.com/966270 . The idea is to create a really simple MVC in js (my first attempt) that i can reuse easily. Improvements are welcome!
JE.events = (function {
// Create closure
// Declare controller and model as local
var Controller = {
init: function(){
$(".monthheader").click(function () {
Model.get($(this).attr('title'));
return false;
});
return this;
}
}
var Model = {
get: function(monthnum){
...
}
}
// return object thats assigned to JE.events
return {
controller: Controller,
model: Model
}
)();
You may also want to look at backbone or spine which are lightweight MVC frameworks.
They give you some simple abstractions and a lot of control. There also small and simple.
If I were to write a micro MVC framework from scratch it would converge to either backbone or spine so it might be better to use one of those two.
I want to migrate the javascript in my site from YU2 to YUI3, but I am only a poor amateur programer and I am stuck at the first pitfall.
I have the following code:
MyApp.Core = function() {
return {
init: function(e, MyAppConfig) {
if (MyAppConfig.tabpanels) {
MyApp.Core.prepareTabpanels(MyAppConfig.tabpanels);
}
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YAHOO.util.Event.addListener(window, "load", MyApp.Core.init, MyAppConfig);
How can I pass the MyAppConfig object to the MyApp.Core.init function by using YUI3 "domready" event listener?
Thanks in advance!
You should be able to do something like:
var MyApp = {};
MyApp.Core = function(){ return {
init: function(MyAppConfig) {
console.log(MyAppConfig);
},
prepareTabpanels: function(tabpanels) {
// Code here
}
}
}();
var MyAppConfig = {
"tabpanels":{"ids":["navigation"]}
};
YUI().use('node', 'event', function(Y){
Y.on('domready', MyApp.Core.init, this, MyAppConfig);
});
Note that the event is not passed in as the first parameter, it is the config.
Y.on accepts parameters as <event_type>, <callback_function>, <context>, <params>..
any parameter after the third item is passed through to the callback function so MyAppConfig becomes the first parameter in your init.
EDIT
See the YUI3 API documentation here: http://developer.yahoo.com/yui/3/api/YUI.html#method_on