Get Javascript objects by class? - javascript

Dojo for instance adds a member to a JS object called "declared_class". I would like to find those and replace some stuff. And, can this be done also outside of Dojo ? I know, JS is not type oriented but you never know whats out to bypass this lack of introspection facilities.
Update : This is NOT about DOM objects. I am writing a sort of real-time Javascript editor. After I reloaded the script, I need to locate related (Dojo modules) objects and mixin altered functions only.
Update 2 : It doesn't seem to be possible without a prototype or a similar patch. Since all the code is running 1:1 in a node instance as well, I am wondering whether I can determine those objecys in a node.js instance ?

Related

How to protect your JS library from being effected by another library modifying the global Object prototype

I'm working on a JavaScript library that gets included in my customers application via a script tag.
Another library they want to include is making changes to the Object.prototype by adding methods setObject and getObject as well as Object.prototype.properties. This interferes with the execution of our code.
I would like to know if it's possible to protect our library for any manipulation of global prototypes, even beyond this specific example.

Use plain Javascript object as Ember model

Is it possible to use a plain JS object (say literal object) as model in EmberJS ?
All the examples that I see in the documentation use Ember.Object (or datastore)
I assume I might not get things like observable, etc using plain JS. But is it at least supported ?
This will not work reliably. A template such as
{{model.prop}}
operates by putting an observer on 'model.prop'. This might work in some cases, but not in others, or you may get weird Ember messages.
Of all the aspects of Ember, the most basic is the Ember object model. Essentially, the entire framework is based on this model and using it to manage objects and retrieve and set properties. Once you've bought into Ember, you've bought into using this object model, which is based on old-fashioned classic inheritance.
A common case where your issue comes up is that a server API returns a plain old JS object as the value of a model property. You then want to dig around inside that object, or display its properties in templates. In such cases, it is probably best to either convert the object to an Ember Object (you can do this with transforms; google and you will find people doing this); or, use embedded models, which is not trivial to do, and may require server-side changes (such as including an ID in the embedded models, although you could theoretically add one yourself in the adapter). The latter is what I have done and the end result was to pretty much maintain my sanity.

Cleanest way to make a proxy/passthrough for a JavaScript object that can be called from Dart

This is admittedly weird, but bear with me:
I'm using Dart's js-interop package so that I can call from Dart into JavaScript.
The system I have to work with has a communication path via a particular global JavaScript object - this object is inserted into the JavaScript context as a way to call into native code, but it's not a true JavaScript object; it's a little hacky.
I can't make a Dart Proxy directly to this object because the Proxy code depends on certain constructors and aspects of the prototype chain that don't exist for this hacky object. Specifically, the JsObject_JsObject function generated by dart2js tries to call "constr.bind.apply" where constr is the constructor of the JS object. This object doesn't have a .bind property since it doesn't inherit correctly from other stuff, and all my attempts to add/fix the prototype chain have failed so far.
If I could fix that, it'd be great. But my other option is to proxy a proxy - make a true Javascript object that wraps and proxies the wacky-hacky-native-object, then a Dart Proxy for that.
I'm curious what the cleanest way to make that JS proxy would be - I'd like to call various functions from Dart, with varying numbers of parameters, and have the calls pass through cleanly to the native object, without having to constantly maintain my JS proxy by making sure any functions added to the native object are added to the proxy.
Does anybody have any great/creepy ideas to make this proxy idiot-proof so that it doesn't need a lot of maintenance, but just automagically redirects calls to the native object?
constr.bind.apply is only call on Js Object creation from Dart. You can simply make a JS function that creates your particular JS Object (for instance createWtfObject()). Once created on JS side (by calling from Dart context.callMethod('createWtfObject')) you should be able to use it without problem from Dart side.

I want to stop using OOP in javascript and use delegation instead

After dabbling with javascript for a while, I became progressively convinced that OOP is not the right way to go, or at least, not extensively. Having two or three levels of inheritance is ok, but working full OOP like one would do in Java seems just not fitting.
The language supports compositing and delegation natively. I want to use just that. However, I am having trouble replicating certain benefits from OOP.
Namely:
How would I check if an object implements a certain behavior? I have thought of the following methods
Check if the object has a particular method. But this would mean standardizing method names and if the project is big, it can quickly become cumbersome, and lead to the java problem (object.hasMethod('emailRegexValidatorSimpleSuperLongNotConflictingMethodName')...It would just move the problem of OOP, not fix it. Furthermore, I could not find info on the performance of looking up if methods exist
Store each composited object in an array and check if the object contains the compositor. Something like: object.hasComposite(compositorClass)...But that's also not really elegant and is once again OOP, just not in the standard way.
Have each object have an "implements" array property, and leave the responsibility to the object to say if it implements a certain behavior, whether it is through composition or natively. Flexible and simple, but requires to remember a number of conventions. It is my preferred method until now, but I am still looking.
How would I initialize an object without repeating all the set-up for composited objects? For example, if I have an "textInput" class that uses a certain number of validators, which have to be initialized with variables, and a class "emailInput" which uses the exact same validators, it is cumbersome to repeat the code. And if the interface of the validators change, the code has to change in every class that uses them. How would I go about setting that easily? The API I am thinking of should be as simple as doing object.compositors('emailValidator','lengthValidator','...')
Is there any performance loss associated with having most of the functions that run in the app go through an apply()? Since I am going to be using delegation extensively, basic objects will most probably have almost no methods. All methods will be provided by the composited objects.
Any good resource? I have read countless posts about OOP vs delegation, and about the benefits of delegation, etc, but I can't find anything that would discuss "javascript delegation done right", in the scope of a large framework.
edit
Further explanations:
I don't have code yet, I have been working on a framework in pure OOP and I am getting stuck and in need of multiple inheritance. Thus, I decided to drop classes totally. So I am now merely at theoretical level and trying to make sense out of this.
"Compositing" might be the wrong word; I am referring to the composite pattern, very useful for tree-like structures. It's true that it is rare to have tree structures on the front end (well, save for the DOM of course), but I am developing for node.js
What I mean by "switching from OOP" is that I am going to part from defining classes, using the "new" operator, and so on; I intend to use anonymous objects and extend them with delegators. Example:
var a = {};
compositor.addDelegates(a,["validator", "accessManager", "databaseObject"]);
So a "class" would be a function with predefined delegators:
function getInputObject(type, validator){
var input = {};
compositor.addDelegates(input,[compositor,renderable("input"+type),"ajaxed"]);
if(validator){input.addDelegate(validator);}
return input;
}
Does that make sense?
1) How would I check if an object implements a certain behavior?
Most people don't bother with testing for method existance like this.
If you want to test for methods in order to branch and do different things if its found or not then you are probably doing something evil (this kind of instanceof is usually a code smell in OO code)
If you are just checking if an object implements an interface for error checking then it is not much better then not testing and letting an exception be thrown if the method is not found. I don't know anyone that routinely does this checking but I am sure someone out there is doing it...
2) How would I initialize an object without repeating all the set-up for composited objects?
If you wrap the inner object construction code in a function or class then I think you can avoid most of the repetition and coupling.
3) Is there any performance loss associated with having most of the functions that run in the app go through an apply()?
In my experience, I prefer to avoid dealing with this unless strictly necessary. this is fiddly, breaks inside callbacks (that I use extensively for iteration and async stuff) and it is very easy to forget to set it correctly. I try to use more traditional approaches to composition. For example:
Having each owned object be completely independent, without needing to look at its siblings or owner. This allows me to just call its methods directly and letting it be its own this.
Giving the owned objects a reference to their owner in the form of a property or as a parameter passed to their methods. This allows the composition units to access the owner without depending on having the this correctly set.
Using mixins, flattening the separate composition units in a single level. This has big name clash issues but allows everyone to see each other and share the same "this". Mixins also decouples the code from changes in the composition structure, since different composition divisions will still flatten to the same mixed object.
4) Any good resources?
I don't know, so tell me if you find one :)

Clarification about Javascript objects inserted into DOM?

I am working on a personal project involving some jQuery / native Javascript programming. I am hoping somebody can clarify an issue I'm seeing with my code. I'm confused about the relationship among objects created in Javascript and objects that are part of the DOM.
When using JQuery UI (the tabs feature), my program behaves differently depending on whether I manipulate my object from Javascript directory, or if I first access it from the DOM API, which leads me to believe that the two references are not equal.
For Example:
myObject = $(document.createElement("div")).attr("id", "tabs");
$("body").append(myObject);
Now, I have found that the following example works correctly:
$("#tabs").tabs();
But the following does not:
$(myObject).tabs();
Am I correct in assuming that the object I am retrieving via $("#tabs") is different or works different than the object I have created manually in Javascript (myObject)?
Is there some mechanism that is invoked once you insert an object into the DOM? Should I not be tinkering with it after I insert it into the DOM, and instead re-retrieve it via its id field?
Creating elements with the raw JS methods is no different to any element referenced with jQuery except that those found by expressions like $(...) are wrapped in a jquery object.
Since you're doing this:
myObject = $(document.createElement("div")).attr("id", "tabs");
you already have a jquery object so you should be able to do this:
myObject.tabs();
By doing:
$(myObject).tags();
you're effectively doing this:
$($(document.createElement(...)...);
and I'm not sure what the expected behaviour of that is.
Also bear in mind you can do this (and should favour this way):
var myObject = $("<div></div>").attr("id", "tabs");
The var makes it local in scope (which is what you want 95% of the time) and you can create arbitrary markup with jquery without using the raw JS methods.

Categories

Resources