JS click event notation - javascript

I'm working through some code a previous developer has written and have came across the following notation:
'.js-enter-new-address click'() {}
The code works but I dont understand why. Can anyone point me to any documentation of how this works? as i've not come across js written in this form before. I would usually expect it to be:
$('.js-enter-new-address').on('click', function(event) {}
Update
I've noticed this code is part of the following, Please see below:
const deliveryAddressComponent = Component.create('.checkout-delivery-address', {
'.js-enter-new-address click'() {},
});

Its part of a javascript object that is send as a parameter of the create function of the Component object.
I don't know what this Component is or does since it's not native js.
Although the definition of the javascript object parameter seems weird it does seem to work as you can see in the snippet below.
var obj = {
'.js-enter-new-address click'() {},
}
console.log(obj);

Related

Javascript function is undefined only in IE11

I'm trying to use a template but just realized that the javascript doesn't work at all in IE.
It fails in several places but here is the first one:
I have this tag, immediately before my </html>:
<script>
document.addEventListener("DOMContentLoaded", function (event) {
navbarToggleSidebar();
navActivePage();
});
</script>
The exception says, "0x800a1391 - JavaScript runtime error: 'navbarToggleSidebar' is undefined occurred"
The javascript file that came with this template was minimized as uses some cracy javascript markup that I've never seen and do not understand. But when I do a find in the whole solution for navbarToggleSidebar I only find this:
JkW7: function (t, e, n) {
"use strict";
Object.defineProperty(e, "__esModule", {
value: !0
});
var i = (n("PExH"), n("juYr"), n("6wzU"), n("e9iq"), n("aWFY"));
! function (t) {
t.keys().map(t)
}(n("pax0")), Object.assign(window, {
masonryBuild: i.a,
navbarToggleSidebar: i.c,
navActivePage: i.b
})
},
I can post the whole file somewhere (just tell me where, it's too long to paste here) if that's helpful because this is clearly just a piece of a huge js thing that I don't understand at all. I like to think I'm fairly decent with js and jquery and this looks greek to me. And it all works beautifully in Chrome and FF.
Can anyone help me figure out what's going on?
Thanks!!
Well n is a callback function t is an array or a list of some kind most likely; so in order for you to figure out what is actually happening in the function you have to figure out where the function was actually invoked. It is much easier to find out what library was used and see if it is hosted anywhere in a non-minified version.
Sometimes this is done intentionally in order to protect developers from other people having an easy time engineering their solutions to programming problems.
Basically in order for anyone to figure out what the function actually does, you would have to print the entire page library, then trace through it, then when you are done after about a month you will have your answer.
Arrays, callback functions, as well as a probably system variable and object literals are used in that function.

Custom Unobtrusive Validation Method Not Firing as Per Documentation

I've been attempting to implement a ASP.NET MVC custom validation method. Tutorials I've used such as codeproject explain that you add data-val-customname to the element. Then jQuery.validate.unobtrusive.js then uses the third segment of the attribute
data-val-<customname>
as the name of the rule, as shown below.
$.validator.addMethod('customname', function(value, element, param) {
//... return true or false
});
However I just can't get the customname method to fire. By playing around I have been able to get the below code to work, but according to all the sources I've read Unobtrusive validation should not work like this.
$.validator.addMethod('data-val-customname', function(value, element, param) {
//... return true or false
});
I've posted an example of both methods
jsfiddle example
Any help would be much appreciated
I've updated my question hopefully to make clearer.
I have finally found got there in the end, but still feels like too much hard work and therefore I've probably got something wrong. Initial I was scuppered by a bug in Chrome Canary 62 which refused to allow the adding of a custom method.
My next issue was having to load jQuery, jQuery.validate and jQuery.validate.unobtrusive in the markup and then isolate javascript implementation in a ES6 class. I didn't want to add my adaptors before $().ready() because of my class structure and loading of the app file independent of jQuery. So I had to force $.validator.unobtrusive.parse(document);.
Despite this I was still having issues and finally debugged the source code and found that an existing validator information that is attached to the form was not merging with the updated parsed rules, and essentially ignoring any new adaptors added.
My final work around and admit feels like I've done too much, was to destroy the initial validation information before my forced re-parse.
Here is the working jsfiddle demo
Here is some simplified code
onJQueryReady() {
let formValidator = $.data(document.querySelector('form'), "validator" );
formValidator.destroy();
$.validator.unobtrusive.adapters.add("telephone", [], function (options) {
options.rules['telephone'] = {};
options.messages['telephone'] = options.message;
});
$.validator.unobtrusive.parse(document);
$.validator.addMethod("telephone", this.handleValidateTelephoneNumber);
}

Querying the DOM in Windows 8 Apps from within a method

I'm struggling with this even after reading the MSDN documentation and the following online guides:
Codefoster
Stephen Walter
I think my problem is easy to fix and that I just am thinking about something in the wrong way. Basically I am querying my web service and on success running the following method. I am then trying to bind the result to my listview. For now I am using a hardcoded value publicMembers.itemlistwhich has been declared at the top of the document just to make sure I can actually bind to the list before doing it with my query results. Ignore line 2 for now.
Success Method:
_lookUpSuccess: function xhrSucceed(Result) {
var response = JSON.parse(Result.responseText);
listView = document.querySelector("#termTest");
ui.setOptions(listView, {
itemDataSource: publicMembers.itemList,
itemTemplate: document.querySelector(".itemtemplate"),
})
},
Now, instead of using document.querySelector, I have also tried with WinJS.Utilities.id and WinJS.Utilities.query, neither of which worked either. This doesn't break my code and introduce an error but it doesn't bind to the listview either so I think I have an issue in querying the right DOM element. However exactly the same code does work if I add it to the top of the script, it is only when I place it in this method that it stops working.
EDIT: Also to clarify, when I debug publicMembers.itemList is storing the values I expect them to be.
Please point out if I have explained things poorly and I will try and improve my question.
Thanks.
I haven't used WinJS.UI.setOptions, but rather this other way of setting the data source. Can you see if it works?
_lookUpSuccess: function xhrSucceed(result) {
var response = JSON.parse(result.responseText);
listView = document.querySelector("#termTest");
listView.winControl.itemDataSource = publicMembers.itemList;
},
This would assume you're defining the itemTemplate as part of the data-win-options attribute of your ListView's HTML element. You could also probably just do listView.winControl.itemTemplate = document.querySelector(".itemtemplate") if you prefer to set it programmatically.

jquery tmpl in a closure

i am working on this little javascript library and following various suggestions i am wrapping my functionality in a closure for the various reasons (encapsulation of variables, hidding of code and so on). since I query a JSON webservice and display the results I also use the jquery tmpl engine.
I think I understand what closures are good for but I sure don't understand them in general. meaning I get totally lost between all those scope changes and whatnot. especially annoying is this exception I get. consider the following code (a simplified ugly version of the code in question, but it reproduces the problem)
// something would be the object that handles all the library functionality
var something = function(){
// creating a local function that goes as a parameter into the Array.filter
function isBar(data){
return data.name === "bar";
}
// the template code
var bla = "<h1>${name}<\h1><h2>${attribute.filter(isBar)[0].value}</h2>";
// precompiling the the template
$.template("test", bla);
// and returning a function that should render the template with the provided data
return {
funny: function(){
$.tmpl("test", [{"name":"Fo", "attribute":[{"name":"bar", "value":"how"}]},
{"name":"Foo", "attribute":[{"name":"fnord","value":"can"}]},
{"name":"Fooo", "attribute":[{"name":"bar","value":"this"}]},
{"name":"Foooo", "attribute":[{"name":"Bar", "value":"be"}]}
]);
}
}
}();
// calling the function
something.funny();
So when calling the something.funny() I would the following expect to happen: the function funny, being a closure gets called in its original context (e.g. the function isBar and the variable bar are defined). So when I call $.tmpl I hoped that attribute.filter(isBar) within the template would also be in this scope. but it isn't. I Chrome i get ReferenceError: isBar is not defined.
If someone would be so nice to show me the error of my ways I would be very happy.
edit oops I missed the "()".
OK, well the problem is that those references to the local variables in the closure are not really references to local variables - they're part of a string. The template code has to parse that string, so when it does that the fact that there was a function called "isBar()" in the closure from where "$.tmpl()" was called really doesn't matter; jQuery can't access them because you just can't do that in JavaScript.
You can, however, pass in an "options" third parameter to "$.tmpl()" and provide extra stuff there. I'm not 100% sure how to do it as I've only played with the template plugin a little bit, but I'll try a jsfiddle when I have a chance. I think that you'd basically do something like this:
funny: function(){
$.tmpl("test", [{"name":"Fo", "attribute":[{"name":"bar", "value":"how"}]},
{"name":"Foo", "attribute":[{"name":"fnord","value":"can"}]},
{"name":"Fooo", "attribute":[{"name":"bar","value":"this"}]},
{"name":"Foooo", "attribute":[{"name":"Bar", "value":"be"}]}
], { isBar: isBar });
}
What I'm not sure of is whether you refer to that as "${isBar()}" or "${item.isBar()}" inside the template text.

"Error calling method on NPObject!" in Uploadify

I'm using Uploadify to upload file in my CMS. Everything works fine until recently. I got an error
Error calling method on NPObject
on this line
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
on this part
uploadifyUpload:function(ID,checkComplete) {
jQuery(this).each(function() {
if (!checkComplete) checkComplete = false;
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
});
},
I don't know why and after a day debugging and testing I found that if I remove replace(/\&/g, '\\&') from
String.prototype.escAll = function(){
var s = this;
return s.replace(/\./g, '\\.').replace(/\?/g, '\\?').replace(/\&/g, '\\&');
};
It then works again. I really don't know why.
Any helps would be appreciated!
I think the reason is in additional Javascript libraries you use.
Some libraries (for example Prototype.js or jQuery.js) change behaviour of your code. For example, you can't overload prototype in some cases. The result may be undefined in clear (obvious) places (like you use an array variable with wrong index). You should view the source code of additional libraries, probably they do with prototype something that breaks your code in the function you mentioned.
In my practice I had the situation when overloading of prototype worked incorrectly (it was String prototype like in your case).
So just don't use prototype.

Categories

Resources