Dynamic proxies in javascript? - javascript

I can proxy a single function in javascript by doing something like this (just jotted down from memory so bear with me)
function addAroundAdvice(target){
var targetFunction = target.aFunction;
target.aFunction = new function(){
invokePreCall();
targetFunction.apply(target, arguments);
invokePostCall();
}
}
Being a java programmer I'd think of this as a dynamic proxy. Every time I write code like this I think that someone must have made a really smart library that does the common proxying operations that is at least 10% better than what I can do in a hurry. I'd be expecting some stuff like correctly intercepting all methods for any given object, which may not be entirely trivial. Then there's different types of advice. So while I'm not expecting something the size of scriptaculous, it's certainly more than 6 lines of code.
So where are these libraries ?

Try jQuery AOP plugin
Looking at the source it seems that only uses jQuery as a namespace, so you could try this plugin even if don't want to use jQuery.

The Dojo Toolkit has a lot of support for AOP constructs like this:
Eugene Lazutkin's Blog Post on Aspect Oriented Programming with Dojo

The fact that you have been able to do it I would think means that there is a library to achieve it in the form of pure JavaScript i.e. your above example. Design Patterns can be applied to JavaScript as you know, so I think the advice I would provide to you is the following by a Google and Yahoo GUI developer :
http://jsdesignpatterns.com/
Chapter 14: The Proxy Pattern. Reference there solution to yours. You may still prefer your approach or you may find tips from their approach.
Cheers,
Andrew

I don't think you can intercept all functions.
The best you can do is iterate over all elements of an object and look for any functions:
for elem in someObject {
if typeof(elem) == "function" {
// replace the function
}
}
Trouble is, that if you add a function later it's not routed through the proxy.

Related

Linq.js Enumerable.from()

I am new to this very very nice Linq.js library that I have just discovered. I am following the examples to write queries like:
Enumerable.from(jsonArray).select(...); // noice
Can I do this shortcut?
jsonArray.select(...); // error as expected
I read the tests in library, seems like pretty much every call starts with Enumerable.someCommand();. I am wondering if the linq commands have been applied to the correct prototypes in js, so I can call them in the style of 2nd line of code. am I not aware of it because I am a newbie?
I am the creator of the open source project http://www.jinqJs.com.
You could simply do jinqJs().from(jsonArray).select();
Let me know if I could be of any more help
If your concern is that Linq.js doesn't extend the Array prototype, I think it's misplaced. It's not exactly a light framework, kinda the same reason why jquery doesn't do the same thing. You shouldn't expect anything to work on just anything.
If you wanted to make bridging that gap a little nicer, it should be safe to add some methods to convert to the other.
if (!Array.prototype.AsEnumerable) { // not likely to be used by others
Array.prototype.AsEnumerable = () => Enumerable.From(this);
}
Then that would allow you to do:
jsonArray.AsEnumerable().Select(...);

What JS library can be selected for RIA REST based application

I have ad idea to make some REST application. I already selected what I will use on server side.
But now I have a big big deal, what i should use to make RICH web app ?
I have middle javascript knowledges. I know jquery, I did my own jquery plugin. it should tell you about my level, so far from pro level.
But i would like to try make it by my self. And i'm thinking that jQuery it's not good choice for this kind of task. I would like to have something more flexible, and not looks like a lot of callback for specific events. Something maybe in MVC style.. But i don't want to spend a lot of hour to lear complicated stuff.
For example: ini PHP life there are a lot of frameworks, I choose Yii, it's really more easier to understand and make something, than Symfony (even 2nd version) for instance.
So i'm looking something similar Yii (but for a browser side), something fast, easy to learn, flexible and powerfull.
I thought maybe it could be cofeescript, or cappuccino or something else ...
BUT I don't have so much time to learn and try so many JS frameworks and libraries to make decision by my self, this is why i'm asking you all.
Thanks.
Typically my choice would be:
jQuery - for general stuff
Q promises library for handling of more
complicated asynchronous operations
Backbone for building model on the
client side
Mustache templates for interaction with HTML
Jasmine - for unit testing of the application
However if you plan to make very rich user interface, you need to handle many various events and you don't want to write your own visual controls (since they are complicated) you can go with ExtJS (note the potencial need to buy licence).
For me Jquery ui has always been easy to use with my limited javascript knowledge .The learning curve wasn't steep at all and lots of community plugins helped in the further development as well .
Apart from that you can try Mootools , Extjs (very nice components but requires a bit learning ) and yui (definite learning required for me ) .
I would recommend using jQuery because you already have some knowledge about it. When it comes jQuery UI it offers some functionality: http://jqueryui.com/demos/. Is this functionality RICH enough?
On top of jQuery, you can use several JS libraries to fullfil specific needs:
Charts:
http://www.highcharts.com/
Grid:
http://www.activewidgets.com/
When you are using JS it's really important that you keep your own JS code in good order. Devide your functionality into separate js-files. Think about your object structure. JS is prototypal language (you can inherit directly from other objects).
For me it took some time to find out the way to write good JS code. I highly recommend this book: JavaScript: The Good Parts (by Douglas Crockford).
// Namespace
var MyNameSpace = {};
MyNameSpace.vehicle = function() {
var that = {};
var my = my || {};
my.thisIsMyOwn;
that.publicFunction = function() {
my.thisIsMyOwn = "put something here";
};
return that;
};
MyNameSpace.car = function() {
var that = MyNameSpace.vehicle(); // "inheritance"
return that;
};

A library to couple with jquery which helps work with classes easily (create/inheritance and so on)

I recently used Ext.JS for a project and I loved it's way to make javascript more "C-like" I may say, with inheritance through keyword "extends" and class definition through Ext.define.
While I love Ext, I don't think it fits well to create a normal website (I like it for management web application), I prefer JQuery for things like that, because usually I have a custom graphic and animation involves a lot of DOM manipulation (with Ext, everything is integrated in their classes).
I would like to couple JQuery with a library that handles only the "class" aspect of javascript. It doesn't need to do anything about jquery, I just need to write my code as something object oriented.
I don't want change my javascript development framework because I already use Ext and JQuery, I think it's enough.
Thanks for suggestion
Edit 1:
Looks like this question is already answering (in part) me.
Because it's a 2009 question, I would like to know if there are other libraries that I should look to.
I'm thinking about using JS.Class, base2 doesn't have (for me) a natural syntax. Joose is doing more than I require and JS.Class is inspired by ruby (which is ok for me). Expecially it looks more natural for me.
I like writing things OOP too. So this is what i do!
(function() {
MySite = {
... some basic functions that involve whatever javascript libraries
}
})();
Then i want make a ui section
MySite.ui = {
uiButton: function($buttons) {
$.each($buttons, function() {
var $this = $(this),
settings = $this.data("settings");
$this.click(function() {
if (settings.type == 0) {
MySite.handleLocationChange(settings.location);
}
});
});
}
}
So thats how i do some stuff, Obviously this is library independent, i just prefer jQuery, for its selector stuff. But i can extend my library with different parts that are easy to implement
So i would have a div
<div class='uiButton'data-settings='{"type":"0"}'>MySweetButton</div>
<script type='text/javascript'>MySite.ui.uiButton($(".uiButton"));(</script>
I solved the problem by myself, it looks like JS.Class works really well coupled with JQuery (obviusly you have to make it work in an OOP way). Here you can find the sources which brought me to this answer:
jquery class inheritance
This expecially:
Has anyone used JS.Class and liked it?

JavaScript messy code in large projects with jquery etc?

Calling the javascript gurus out there.
Basically my question is regarding how you structure your code, both visually and for functionality for example do you wrap everything in objects using this structure:
var myapp={
binds:function(){
//put some event listeners for jquery etc...
},
otherfunc:function(){
//do some other thing
},
init:function(){
//call myapp.binds and other functions and other stuff to intialize your app.
}
};
Then finally
$(document).ready(myapp.init);
The thing is with a structure like this I think JSLint complains doesn't it? Whats the pros and cons using a structure like this or is there a generally better way to structure your code? Do you follow a certain pattern from $(document).ready(call) to putting all your event listeners and "initializing" your app, do you use separate objects for methods and variables?
I also think "visually" if you have a very large webapp this structure eventually looks very messy, but maybe it's just me I don't know, any input is appreciated thanks.
Using Inheritance Patterns to Organize Large jQuery Applications
explain in detail and with better practice by Alex
http://alexsexton.com/?p=51
its very very well explain, must see
other links
How To Manage Large jQuery Apps 5 months ago
It doesn't matter much how you structure your code as long as you follow the essentials rules of programming that your teacher thought you:
Don't write repetitive code
A function must do 1 and only 1 thing
Document your code
Some other small things but mostly the above... oh and apply lots of common sense
The only error you get from that is "implied global." You can get rid of the warning for document by using this.document instead (since window is the context). The implied global for $ will stay unless you paste in the jQuery source (then gl with all the errors in that).
I trust JSLint--a lot. On big projects I tend to make object literals as you did above but I use a module pattern for object security:
var myapp = (function () {
var secret_stuff, public_stuff;
return {
stuff: public_stuff
}
}());

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources