So I have this Omniture object. It's called s.
s
Inside s, we keep track of a bunch of information, inside "props" and "eVariables".
s.prop5 = 'foo'
s.prop22 = 'baz'
s.var6 = 'bar'
Which prop variables and which evars we choose to assign, depends on which page we're tracking.
For example, on the homepage, we may wish to track prop5, prop6, and evar2, but on the registration page, we may wish to track prop4, prop5, prop9, prop10, evar4, evar5. It varies.
Each variable and each prop represents some kind of key analytics information.
Now, even though this solution is not ideal, because the prop#s can all blend together, we do have a master list that we keep internally, explaining which variable represents what.
prop5 means "page name"
prop6 means "page category"
(et cetera)
Now, this is fine, and it works well enough, but we often have to pass the code off to third parties so they can assign values themselves. We might have a 3rd party create a page, and we want to do analytics on it, but we need them to be able to get the appropriate information to track. To make it more readable, we were considering of implementing some mapping code.
companyName.pageName = 'This is the page name'
companyName.contentType = 'This is the content type'
companyName.campaignId = 'This is the campaign ID'
This is more readable. We would then loop through the "companyName" object, and assign every value back to 's' where appropriate.
What do you guys think? Would this be a good practice?
Honestly I can't see why you would use the cryptic property names in the first place. Why not use the names you would give to 3rd parties internally as well. Wouldn't it just make your life easier?
Related
I'm running circles here and I'm out of idea's/google searches. There are so many different examples but all seem to do something different or don't work. According to shopify, this is the only documentation I can find around using their API: https://shopify.dev/tutorials/customize-theme-use-products-with-multiple-options
A ghost object I see, no matter, more and more searches I still can't figure out what this parameter is supposed to be.
I've attempted passing a json object of products as I've seen it done in various other theme examples:
var product = document.querySelector("[data-product-json]").innerHTML,
product = JSON.parse(product || '{}');
console.log(product);
jQuery(function($) {
new Shopify.OptionSelectors('productSelect-' + product.id, {
product: product,
onVariantSelected: selectCallback
});
});
The console log gives the correct object and json, nice.
OptionSelectors errors out:
Uncaught TypeError: Cannot read property 'parentNode' of null
at Shopify.OptionSelectors.replaceSelector (option_selection-fe6b72c2bbdd3369ac0bfefe8648e3c889efca213baefd4cfb0dd9363563831f.js:1)
at new Shopify.OptionSelectors (option_selection-fe6b72c2bbdd3369ac0bfefe8648e3c889efca213baefd4cfb0dd9363563831f.js:1)
I've given it just the product.id and various other things.
I'm going to out on a whim here and say the Shopify documentation is detailed, yes, but it is not developer-friendly in my opinion. They give you so much information but never what you really need.
Shopify products have a pretty simple, but weird in a way organization. First off, a product has an array of up to three things known as options. Can be empty. But as soon as you assign an option to a variant, this gets filled in. So you have your three options. Eg: Name, Size, Color, Material and on and on.
A variant has the actual value of the options. So if you provided option 1 as Size, a variant would have option1 equal to a size value, like "large". Repeat and layer in the other options, till a variant perhaps has 3. Now, reverse that process to simply get an ID so you can update a price, or some other logic!
So in this way, up to 100 variants can have 3 distinguishing options, all different. Going way back to Shopify early days, they produced some code that ended up lasting about ten years, and your snippet of OptionSelectors is an offshoot of that mess.
The challenge is to do what that old code did, but for your theme purposes. Many libraries and themes have done just that. But be aware they also used code that is not exactly easy to fork and use for your own purposes either.
So if you find hacking this old Shopify code to be a mind-numbing experience, you might do better to just rebuild Humpty Dumpty yourself so you completely understand it. You do not need to use their code. It is also super confusing because when Theme authors spawn yet another version of this code, they often thought they'd be clever and rename a few things or target a few different things, and thus establish themselves as "unique, more skilled" players, but in fact, this just adds to your misery, as they did not accomplish much.
So yes, all the best to you in your endeavors. Taking apart that code and learning it is a rite of passage most theme authors undergo. Yes, they swear. Yes it reveals some WTF moments. But in the end, you'll control your variants, and achieve glory.
I strongly recommend David Lazar's answer and that you take some time to build your own function(s) that can do the job of breaking down a product's options and associated values into customer-friendly options and then translating those selections into a single valid variant ID. It's not too hard and sometimes kinda fun.
However, if you just want to get the OptionSelectors code working:
var product = document.querySelector("[data-product-json]").innerHTML,
product = JSON.parse(product || '{}');
console.log(product);
jQuery(function($) {
new Shopify.OptionSelectors('productSelect-' + product.id, {
product: product,
onVariantSelected: selectCallback
});
});
The first parameter that goes into the function is the ID of the (usually hidden) element inside your form that will store the value of the ID of the selected variant.
The error you are getting from the OptionSelectors code:
Uncaught TypeError: Cannot read property 'parentNode' of null
is most often thrown when the code doesn't find that element.
So to fix your problem, in your product form you should just need to find (or create) an input field with name="id" and make sure that element has an ID that matches what you're using.
For example:
<input type="hidden" id="productSelect-{{ product.id }}" name="id" value="{{ product.selected_or_first_available_variant.id }}" />
(Alternatively, find your input with name="id" and take the ID attribute from that field and use it in your call to OptionSelectors)
The problem you will encounter is that different themes change what they pass. You are better off creating your own event handler to get the variant id and lookup the variant details that your code requires.
See Shopify trigger function on variant selection but don't override existing functionality for some tips on how to set that up.
So i've been asked to remake some registration forms. The way its supposed to work is, that an interpreter chooses X amount of languages in the first select box. Then based on the selections of languages, the user must specify from which languages they can translate from/to.
I want to store this data in a key/value array, with the key being "LanguageFrom" and Value being another array, of "LanguagesTo". This is how i have solved this:
function btnTest() {
var fromArray = $('.freelancerLanguagesFrom').map(function() {
return $(this).val();
}).get();
var toArray = $('.freelancerLanguagesTo').map(function() {
return $(this).val();
}).get();
var tempArray = {};
tempArray[fromArray] = toArray;
}
This method is being called with an "onclick" function in the html part. The user should specify which languages he can translate to for each of the chosen languages in the first box,
I am aware that this probably isn't the ideal approach, but im still an inexperienced developer, and i'd love to hear your take on another approach.
Now comes my problem:
1) How do i make it so the array wont overwrite the existing array with each button click, and instead just add to the array?
2) How do i process this array on the server side (php), so that i can store the values in my database?
3) Is it possible to skip the flow where the user has to press the save(gem) button after each language he has chosen?
edit: Question 1 and 3 are now solved, my only problem is accessing the array i made in js, on the php side
1) tempArray exists only in the scope of the btnTest() function. Declare it outside (in the global scope), initialize it as {} and don't reset it every time you click the button. The way you get the fromArray variable may require some tweaking depending on whether the "from" list can accept a multiple selection or not.
2) Ajax may help. Create a php endpoint to receive the request and call it using ajax. You can work on the array using JSON. Send your data using JSON.stringify(tempArray) and read it using json_decode() in your php script, or simply set the request headers as "application/json" to have it done automatically for you.
3) I personally wouldn't automate this process. Let's say I have 4 languages, Italian, English, French and Chinese.
I have selected a desirable state of languages I can handle:
Italian -> English, French
But I also know how to translate French in Italian so I click, in the from list, French, and I get
French -> English
Which is an undesirable state, for me, because I don't know how to do that. Especially if I were to select many languages, I'd get, inbetween 2 states I want to save, an indefinite amount of states I don't want to save.
If you still want to do so, you need to move the even listener from the button to the list(s), with the onchange event.
I'd also suggest you do your event binding trough jQuery, if you aren't already.
Hope this helped.
Say you have a very simple data structure:
(personId, name)
...and you want to store a number of these in a javascript variable. As I see it you have three options:
// a single object
var people = {
1 : 'Joe',
3 : 'Sam',
8 : 'Eve'
};
// or, an array of objects
var people = [
{ id: 1, name: 'Joe'},
{ id: 3, name: 'Sam'},
{ id: 8, name: 'Eve'}
];
// or, a combination of the two
var people = {
1 : { id: 1, name: 'Joe'},
3 : { id: 3, name: 'Sam'},
8 : { id: 8, name: 'Eve'}
};
The second or third option is obviously the way to go if you have (or expect that you might have) more than one "value" part to store (eg, adding in their age or something), so, for the sake of argument, let's assume that there's never ever going to be any more data values needed in this structure. Which one do you choose and why?
Edit: The example now shows the most common situation: non-sequential ids.
Each solution has its use cases.
I think the first solution is good if you're trying to define a one-to-one relationship (such as a simple mapping), especially if you need to use the key as a lookup key.
The second solution feels the most robust to me in general, and I'd probably use it if I didn't need a fast lookup key:
It's self-describing, so you don't
have to depend on anyone using
people to know that the key is the id of the user.
Each object comes self-contained,
which is better for passing the data
elsewhere - instead of two parameters
(id and name) you just pass around
people.
This is a rare problem, but sometimes
the key values may not be valid to
use as keys. For example, I once
wanted to map string conversions
(e.g., ":" to ">"), but since ":"
isn't a valid variable name I had to
use the second method.
It's easily extensible, in case
somewhere along the line you need to
add more data to some (or all) users.
(Sorry, I know about your "for
argument's sake" but this is an
important aspect.)
The third would be good if you need fast lookup time + some of the advantages listed above (passing the data around, self-describing). However, if you don't need the fast lookup time, it's a lot more cumbersome. Also, either way, you run the risk of error if the id in the object somehow varies from the id in people.
Actually, there is a fourth option:
var people = ['Joe', 'Sam', 'Eve'];
since your values happen to be consecutive. (Of course, you'll have to add/subtract one --- or just put undefined as the first element).
Personally, I'd go with your (1) or (3), because those will be the quickest to look up someone by ID (O logn at worst). If you have to find id 3 in (2), you either can look it up by index (in which case my (4) is ok) or you have to search — O(n).
Clarification: I say O(logn) is the worst it could be because, AFAIK, and implementation could decide to use a balanced tree instead of a hash table. A hash table would be O(1), assuming minimal collisions.
Edit from nickf: I've since changed the example in the OP, so this answer may not make as much sense any more. Apologies.
Post-edit
Ok, post-edit, I'd pick option (3). It is extensible (easy to add new attributes), features fast lookups, and can be iterated as well. It also allows you to go from entry back to ID, should you need to.
Option (1) would be useful if (a) you need to save memory; (b) you never need to go from object back to id; (c) you will never extend the data stored (e.g., you can't add the person's last name)
Option (2) is good if you (a) need to preserve ordering; (b) need to iterate all elements; (c) do not need to look up elements by id, unless it is sorted by id (you can do a binary search in O(logn). Note, of course, if you need to keep it sorted then you'll pay a cost on insert.
Assuming the data will never change, the first (single object) option is the best.
The simplicity of the structure means it's the quickest to parse, and in the case of small, seldom (or never) changing data sets such as this one, I can only imagine that it will be frequently executed - in which case minimal overhead is the way to go.
I created a little library to manage key value pairs.
https://github.com/scaraveos/keyval.js#readme
It uses
an object to store the keys, which allows for fast delete and value retrieval
operations and
a linked list to allow for really fast value iteration
Hope it helps :)
The third option is the best for any forward-looking application. You will probably wish to add more fields to your person record, so the first option is unsuitable. Also, it is very likely that you will have a large number of persons to store, and will want to look up records quickly - thus dumping them into a simple array (as is done in option #2) is not a good idea either.
The third pattern gives you the option to use any string as an ID, have complex Person structures and get and set person records in a constant time. It's definitely the way to go.
One thing that option #3 lacks is a stable deterministic ordering (which is the upside of option #2). If you need this, I would recommend keeping an ordered array of person IDs as a separate structure for when you need to list persons in order. The advantage would be that you can keep multiple such arrays, for different orderings of the same data set.
Given your constraint that you will only ever have name as the value, I would pick the first option. It's the cleanest, has the least overhead and the fastest look up.
I have a Person class where edits made to the person must be verified by an admin user.
Each attribute has an "approved" and "tmp" version. Sometimes the "tmp" version is not set:
person = {first:'Bob', firstTmp:'Robert', last:'Dobbs', lastTmp:undefined}
When displaying the person, I want to display the "tmp" value if it is set, otherwise display the "approved" value. When writing, I want to write to the "tmp" value (unless logged in as an admin).
Ideally, this would not require a lot of custom markup, nor writing cover methods for each property (there are around 100 of them). Something like this would be nice:
<input ng-model="person.first"
tmp-model="person.firstTmp"
bypass-tmp="session.user.isAdmin" />
When displaying the value, display the tmp value if it is defined. Otherwise display the approved value.
When writing the value, write to the tmp value, unless logged in as an admin. Admins write directly to the approved value.
What's a good clean way to implement this in Angular?
Extend NgModelController somehow?
Use a filter/directive on the input?
Cover methods?
Just do the writing server-side?
I will try to go through your options one by one:
Extend NgModelController somehow?
I don't think this is a good idea. It won't be nice if something goes wrong and you don't know if you can even rely on something as basic as ng-model
Just do the writing server-side?
This would seem like the easier way (if you already know or find it easy to manage it in the back end), although the interaction would need a new request to the server.
Use a filter/directive on the input?
I believe this would be the best way to do it, as it is easy to understand what is going on by just taking a look at the markup. It's angular, you already know that some property like tmp-model is extending the markup.
Cover methods?
This would also be easy to implement, and you would be implementing some sort of "business logic" as a validator in your cover method.
Given that I've extended a bit in my answer, I can give you an inline example of the last one.
<input ng-model="person.firstTmp"
ng-init="person.firstTmp = person.firstTmp || person.first"
ng-change="updateProperty(person, 'first')" />
And on the controller, you could do something like:
$scope.updateProperty = function(person, propertyName) {
// The temporary property has already been changed, update the original one.
if($scope.session.user.isAdmin)
person[propertyName] = person[propertyName + 'Tmp'];
}
I have a scenario on my web application and I would like suggestions on how I could better design it.
I have to steps on my application: Collection and Analysis.
When there is a collection happening, the user needs to keep informed that this collection is going on, and the same with the analysis. The system also shows the 10 last collection and analysis performed by the user.
When the user is interacting with the system, the collections and analysis in progress (and, therefore, the last collections/analysis) keep changing very frequently. So, after considering different ways of storing these informations in order to display them properly, as they are so dynamic, I chose to use HTML5's localStorage, and I am doing everything with JavaScript.
Here is how they are stored:
Collection in Progress: (set by a function called addItem that receives ITEMNAME)
Key: c_ITEMNAME_Storage
Value: c_ITEMNAME
Collection Finished or Error: (set by a function called editItem that also receives ITEMNAME and changes the value of the corresponding key)
Key: c_ITEMNAME_Storage
Value: c_Finished_ITEMNAME or c_Error_ITEMNAME
Collection in the 10 last Collections (set by a function called addItemLastCollections that receives ITEMNAME and prepares the key with the current date and time)
Key: ORDERNUMBER_c_ITEMNAME_DATE_TIME
Value: c_ITEMNAME
Note: The order number is from 0 to 9, and when each collection finishes, it receives the number 0. At the same time, the number 9 is deleted when the addItemLastCollections function is called.
For the analysis is pretty much the same, the only thing that changes is that the "c" becomes an "a".
Anyway, I guess you understood the idea, but if anything is unclear, let me know.
What I want is opinions and suggestions of other approaches, as I am considering this inefficient and impractical, even though it is working fine. I want something easily maintained. I think that sticking with localStorage is probably the best, but not this way. I am not very familiar with the use of Design Patterns in JavaScript, although I use some of them very frequently in Java. If anyone can give me a hand with that, it would be good.
EDIT:
It is a bit hard even for me to explain exactly why I feel it is inefficient. I guess the main reason is because for each case (Progress, Finished, Error, Last Collections) I have to call a method and modify the String (adding underline and more information), and for me to access any data (let's say, the name or the date) of each one of them I need to test to see which case is it and then keep using split( _ ). I know this is not very straightforward but I guess that this whole approach could be better designed. As I am working alone on this part of the software, I don't have anyone that I can discuss things with, so I thought here would be a good place to exchange ideas :)
Thanks in advance!
Not exactly sure what you are looking for. Generally I use localStorage just to store stringified versions of objects that fit my application. Rather than setting up all sorts of different keys for each variable within localStore, I just dump stringified versions of my object into one key in localStorage. That way the data is the same structure whether it comes from server as JSON or I pull it from local.
You can quickly save or retrieve deeply nested objects/arrays using JSON.stringify( object) and JSON.parse( 'string from store');
Example:
My App Object as sent from server as JSON( I realize this isn't proper quoted JSON)
var data={ foo: {bar:[1,2,3], baz:[4,5,6,7]},
foo2: {bar:[1,2,3], baz:[4,5,6,7]}
}
saveObjLocal( 'app_analysis', data);
function saveObjLocal( key, obj){
localStorage.set( key, JSON.stringify(obj)
}
function getlocalObj( key){
return JSON.parse( localStorage.get(key) );
}
var analysisObj= =getlocalObj('app_analysis');
alert( analysisObj.foo.bar[2])