Why data binding doesn't always work with primitives? - javascript

One of the milestones in learning JS and Angular, is learning that two way data binding with primitives is tricky. If you want to make sure that databinding works, you should always pack it into an object - that is what I was told by some seniors in my company. My question is - why is that happening? What is exactly going on that makes databinding with primitives so compliated in JS?
I found out that Javascript passes objects by reverence, and primitives by value. So what exactly happens in for example AngularJS Controller, that enables us to bind primitive in ngModel?
EDIT
Any articles, pointers are more than welcome!

Here is good post or post.
In short:
"Primitive values (e.g. numbers, strings) are immutable in JavaScript. So whenever a change is made to them it means we are actually throwing away the previous instance and using a different one."

Related

JavaScript factory for polymorphic objects approach

I am trying to build up a jQuery plugin using a factory approach since I need two differing objects with the same API. However, most of the examples I see use an inheritance method where some prefabbed object is constructed and then modified according to that objects needs. My question is, why is every approach I've seen some prefabbed object being constructed and then modified rather than simply building the object according to the options and then returning the public side of it using closures as a hook back into the private state of said object.
I don't think this is a duplicate, I have been looking around for my answer and have been fairly unlucky so far
Examples that clearly show what I mean:
- 1
- 2

Using OrderedMap.merge to translate Objects to OrderedMaps instead of Maps?

I'm trying to use OrderedMap.merge to store application state using reflux (specifically reflux-immutable), but I noticed this does not translate Objects into OrderedMaps, but regular Maps, which do not guarantee order when iterated over. There are several parts of my application where I need order to be retained, so I was wondering if there was a way to accomplish this using OrderedMap.merge or something like merge. I came up with this, but it's super ugly and relies on ripping source code out of Immutable.js, which I'm not comfortable with.
Does anyone have any other ideas? Thanks in advance.
I decided to solve this problem a different way, namely by explicitly converting the objects I needed to be ordered maps prior to invoking OrderedMap.merge on the entire store's state. This works because the definition of merge essentially ignores objects that are already immutable, so there's no risk of duplicate work and merge's functionality is retained without having to do all the silly hacked together stuff I was doing.

localStorage - use getItem/setItem functions or access object directly?

Are there some benefits of using the methods defined on the localStorage object versus accessing the object properties directly? For example, instead of:
var x = localStorage.getItem(key);
localStorage.setItem(key, data);
I have been doing this:
var x = localStorage[key];
localStorage[key] = data;
Is there anything wrong with this?
Not really, they are, basically, exactly the same. One uses encapsulation (getter/setter) to better protect the data and for simple usage. You're supposed to use this style (for security).
The other allows for better usage when names(keys) are unknown and for arrays and loops. Use .key() and .length to iterate through your storage items without knowing their actual key names.
I found this to be a great resource : http://diveintohtml5.info/storage.html
This question might provide more insight as well to some: HTML5 localStorage key order
Addendum:
Clearly there has been some confusion about encapsulation. Check out this quick Wikipedia. But seriously, I would hope users of this site know how to google.
Moving on, encapsulation is the idea that you are making little in and out portals for communication with another system. Say you are making an API package for others to use. Say you have an array of information in that API system that gets updated by user input. You could make users of your API directly put that information in the array... using the array[key] method. OR you could use encapsulation. Take the code that adds it to the array and wrap it in a function (say, a setArray() or setWhateverMakesSense() function) that the user of your API calls to add this type of information. Then, in this set function you can check the data for issues, you can add it to the array in the correct way, in case you need it pushed or shifted onto the array in a certain way...etc. you control how the input from the user gets into the actual program. So, by itself it does not add security, but allows for security to be written by you, the author of the API. This also allows for better versioning/updating as users of your API will not have to rewrite code if you decide to make internal changes. But this is inherent to good OOP anyhow. Basically, in Javascript, any function you write is a part of your API. People are often the author of an API and it's sole user. In this case, the question of whether or not to use the encapsulation functions is moot. Just do what you like best. Because only you will be using it.
(Therefore, in response to Natix's comment below...)
In the case here of JavaScript and the localStorage object, they have already written this API, they are the author, and we are its users. If the JavaScript authors decide to change how localStorage works, then it will be much less likely for you to have to rewrite your code if you used the encapsulation methods. But we all know its highly unlikely that this level of change will ever happen, at least not any time soon. And since the authors didn't have any inherent different safety checks to make here, then, currently, both these ways of using localStorage are essentially the same. Except when you try to get data that doesn't exist. The encapsulated getItem function will return null (instead of undefined). That is one reason that encapsulation is suggested to be used; for more predictable/uniform/safer/easier code. And using null also matches other languages. They don't like us using undefined, in general. Not that it actually matters anyhow, assuming your code is good it's all essentially the same. People tend to ignore many of the "suggestions" in JavaScript, lol! Anyhow, encapsulation (in JavaScript) is basically just a shim. However, if we want to do our own custom security/safety checks then we can easily either: write a second encapsulation around the localStorage encapsulate, or just overwrite/replace the existing encapsulation (shim) itself around localStorage. Because JavaScript is just that awesome.
PT
I think they are exactly the same, the only thing the documenation states is:
Note: Although the values can be set and read using the standard
JavaScript property access method, using the getItem and setItem
methods is recommended.
If using the full shim, however, it states that:
The use of methods localStorage.yourKey = yourValue; and delete
localStorage.yourKey; to set or delete a key is not a secure way with
this code.
and the limited shim:
The use of method localStorage.yourKey in order to get, set or delete
a key is not permitted with this code.
One of the biggest benefits I see is that I don't have to check if a value is undefined or not before I JSON.parse() it, since getItem() returns NULL as opposed to undefined.
As long as you don't use the "dot notation" like window.localStorage.key you are probably OK, as it is not available in Windows Phone 7. I haven't tested with brackets (your second example). Personally I always use the set and get functions (your first example).
Well, there is actually a difference, when there is no local storage available for an item:
localStorage.item returns undefined
localStorage.getItem('item') returns null
One popular use case may be when using JSON.parse() of the return value: the parsing fails for undefined, while it works for null

Knockout/MVVM Design Concern

I am struggling with a problem that keeps cropping up when working with the KnockoutJS framework and MVVM in general. There are times when a property on a specific item in a collection changes and because of that change, I need to affect all the other items in that same collection. In all languages and patterns, an object isn't supposed to "know" anything about the collection it's in, but I find myself needing to break that rule often to get certain kinds of logic to work.
I have created a contrived example of what I'm talking about to demonstrate the hacky sort of way I've been solving this problem. I'm hoping someone with more experience can weigh in and show me the better way to do this.
JSFiddle Contrived Example
I don't know whether this is the "recommended" approach, but I will offer my advice of how I would tackle this issue. I am not a MVVM expert (though I've written quite a few KnockoutJS apps), but I think some OOP principles will be more than enough to help here.
So first let's discuss the current state of things...
Your approach, as you correctly observed (knockout pun unintentional!), is not ideal - the Person objects are aware not just of their siblings (even if indirectly via a subscription) but also the parent object to which they are subscribing - Your Person type is subscribed to changes on the parent. Not only does this make your Person object unusable outside of this scenario, it also gives each instance too much responsibility (violating the Single Responsibility Principle) and each instance is subscribed to changes on every other instance, which is of course wasteful!
So what's the solution?
To me the ideal place to put this kind of logic is on your parent object (i.e. your view model). Your view model already has knowledge of it's child objects, so why not put the functionality there? This would make your Person type reusable elsewhere (OK so it has observables, so it's tied to KO at the moment, but this can be overcome with the Mapping plugin) and relieves it of the responsibility of managing its siblings.
But still this means that you have tight coupling between parent and child - not what we want in OOP! To overcome this, you can adopt a pub/sub (observer) pattern and have your Person type publish a message whenever something changes, then you can let a subscriber (e.g. you view model) decide how to respond to this event. You need not necessarily use knockout's pub/sub offerings either, any pub/sub implementation will do. Though you may as well take advantage of what KO offers, so I would point you in the direction of these extensions/helpers to ease things a little: http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html
Hope I've been of help :)
Unless I misunderstood your scenario, you could use computed observables that update on the fly automatically.
First, I figured the 'underage' property flag for each person would just be a calculation of their age compared to a min. age. e.g. 19.
Second, You can also use a computed observable to do an aggregate flag for all users.
Lastly, I wouldn't necessarily agree that this is a parent/child relationship. These are just properties of the view model specific to the page.
Check out this example that uses computed's for both cases.
http://codepen.io/anon/pen/ufKCo

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 :)

Categories

Resources