can.js validate method not working - canjs

Could anybody help me calling a validation function in can.js?
I'm adding can.jquery.js and can.map.validations.js
and then create such a small example:
var mymap = can.Map.extend({
init: function () {
this.validatePresenceOf('myfield'); // this line reports an error
}
});
when loading page with this script, I get an error in browser:
"Uncaught TypeError: undefined is not a function"
Actually any this.validate* function does not work
After some research I notice that when I put this code under
$(document).ready{}
it works, but if I put it into .js file and load via tag - browser reports an error.
And I'm not going to write all of my js code in the page itself

see here it tells pretty clearly(helped me last time) that you have to use $document.ready() or else it wont work, so try making a new file.js, have $document.ready() contain all your todo-code, and link it up, I hope I am helpful in this regard, if not then bug me up I wont mind at all :) ..

Commenting it late but anyway - it didn't work for me in either case so I just took the sample from http://jsbin.com/jofeq/5/edit?html,js,output - and copied it to my code. Surprisingly it worked after copying - not sure what was wrong on my side.
In that example it looks like this:
var Person = can.Map({
init: function () {
this.validatePresenceOf('firstName');
this.validatePresenceOf('lastName');
}
}, {});
and it works without document.ready tricks or anything else - just included into body tag

Related

How to use Jest to test React rendered async data?

I am using React for render and Jest/Jasmine for test. I have test written using old Jest/Jasmine waitsFor and runs but these are gone now in Jasmine 2 and I am not sure how to replace with new done asyncs.
In my code React renders a small page about a user. That page has an AJAX call to fetch user posts. I want to test that user posts have come back nice, and waitsFor was very, very good at this: wait until user has some post, then continue.
I looked online at lots of people talking about using AJAX calls inside Jest test which is not what I want. My Jest test has no idea about AJAX call being made, so I need a way to wait until results come back.
Here is my current code with waitsFor and runs:
it('loads user post', () => {
var page = TestUtils.renderIntoDocument(
<UserPage params={{user: 'fizzbuzz', 'pass': 'xxx'}} />
);
waitsFor(() => {
return page.state.posts.length > 0;
}, "post loaded", 10000);
runs(() => {
var posts = TestUtils.scryRenderedDOMComponentsWithClass(page, 'post');
expect(posts.length).toEqual(10);
});
});
How can I delete the waitsFor and runs and replace with Jasmine 2.0 code that works? All Jest test knows is that page.state.posts.length must be greater than 0 before expecting anything.
You should refactor this test into two unit tests that will provide a more rigorous testing of your code. It would make the tests more independent of one another and help identify errors in a more refined scope. These won't be exact as I do not know what your code is like, but here's something along the lines I would expect to see: -
it('generates the expected properties for a page', function () {
var page = TestUtils.renderIntoDocument(
<UserPage params={{user: 'fizzbuzz', 'pass': 'xxx'}} />
);
expect(page.someProperty).toBeDefined();
expect(page.user).toEqual('fizzbuzz');
});
it('generates the correct number of posts from a given page object', function () {
var fakePage = {
// put your fake mock data here that TestUtils expects
};
var posts = TestUtils.scryRenderedDOMComponentsWithClass(fakePage, 'post');
expect(posts.length).toEqual(10);
});
I am not too sure what is happening in your renderIntoDocument function so the top test may be a little broken... It looks like there is either too much going on inside the function, or you need to test the calls that function is making instead. If you elaborate on what it does I'll edit the answer.

Post forms with coffescript/ ajax in play

I try to submit a simple form with coffeescript/ajax in play. But I'm doing something wrong and can't figure out what.
I started with a working form for creating questions (without ajax) and then followed Playframwork doc on javascript routing:
So first I created the router resource in my Application controller:
def javascriptRoutes = Action { implicit request =>
Ok(
Routes.javascriptRouter("jsRoutes")(
routes.javascript.Questions.create
)
).as("text/javascript")
}
added in routes:
GET /javascriptRoutes controllers.Application.javascriptRoutes
added to my template:
<script type="text/javascript" src='#routes.Application.javascriptRoutes()'></script>
and then included the coffescript:
$ ->
$('#save').on "click", (e) ->
jsRoutes.controllers.Questions.create.ajax
data: $('#questionForm').serialize()
success: (data) ->
alert("success")
error: (err) ->
alert("error")
#save points to a link and the onclick event works for a simple alert. $('#questionForm').serialize() also seems to output the right data.
The script simply does nothing and I don't know how to debug it properly with the chrome javascript debugger as I don't know where to look. At least intellij
tells me that Questions.create is never called.
edit: Thanks to Infinity I noticed that the chrome javascript debugger throws:
Uncaught TypeError: jsRoutes.controllers.Questions.create.ajax is not a function(anonymous function) # save.coffee:3m.event.dispatch # jquery.js:4641m.event.add.r.handle # jquery.js:4309
Thanks to Infinity and the new console error input I noticed that
jsRoutes.controllers.Questions.create.ajax
must be
jsRoutes.controllers.Questions.create().ajax

Issues with angular $watch and retrieving data from database

I'm a novice programming trying to put together a web application with Angular, node.js, and the graph database neo4j.
I would like to load content from my database dynamically based on the user selecting (or rejecting) terms (clicking buttons). Every time a button is clicked the relevant term is added to an array (either exclude or include). The idea is a new call to the database would be made each time a new term is selected.
I'm stuck right now on how to go about making calls to the database to retrieve the content. I'm trying to watch the arrays for changes using $watch. Something is going wrong and I'm having issues troubleshooting the problem.
Here is the controller code:
angular.module('myApp.controllers', []).
controller('content',function($scope,$http, queryTerms, $watch){
//watch arrays of terms for changes and fetch results based on what is selected
$watch(function() { return angular.toJson( [ queryTerms.includedTerms, queryTerms.excludedTerms ] ) },
function() {
$http({
method:'get',
url:'/query/getContent',
params: {includeTerms:queryTerms.includedTerms , excludeTerms:queryTerms.excludedTerms}
}).
success(function(data){
//feed content data to display for viewing
}).
error(function(data){
$scope.test = "Error :("
});
});
});
I'm getting the following error when I use $watch:
Error: Unknown provider: $watchProvider <- $watch
Is this a terrible stupid way to go about this in general? Any advice would be greatly appreciated- I'm learning as I'm going and so far the advice I've gotten on here has be amazing. Thanks!
Use $scope.$watch instead.
controller('content', function ($scope, $http, queryTerms) {
$scope.$watch(function () {
return angular.toJson([queryTerms.includedTerms, queryTerms.excludedTerms])
},...

basic ajax function not working

i'm learning Ajax and i'm facing some problem with this very basic function:
function fetchData(url, objectID){
var pageReqtest=null;
if(window.XMLHttpRequest)pageRequest=new XMLHttpRequest();
if(window.ActiveXObject)pageRequest=new ActiveXObject("Microsoft.XMLHTTP");
else return false;
pageRequest.onreadystatechange= function(){
var object=document.getElementById(objectID);
object.innerHTML = pageRequest.responseText;
}
pageRequest.open("GET",url,true);
pageRequest.send(null);
}
And then i have:
<div id="control" onclick="fetchData('data.jsp','message');">Click here for Ajax!</div>
But unfortunatelly its not working, the function though is correctly called.
I have my project in Eclipse and i'm running this on Tomcat 6, the page data.jsp its a single line of html, the data.jsp is positioned at the same lavel as the page where the javascript function is written
Do you have some advice?
beside wrong spelling as mentioned by lonesomeday
you also have missing parameter here var object=document.getElementById();
Looks like others beat me to it, but in any case, here is working fiddle: http://jsfiddle.net/smendola/BcMMn/
As they said, typos...
My best bet is that it is a syntax error caused by your misspelling of function:
pageRequest.onreadystatechange= fucntion(){
This would cause the Javascript not to be parsed, so your function would never be defined.
On a different note, there are a couple of other little errors that, while they might not prevent your code working, might make your life difficult.
var pageReqtest=null;
Elsewhere you call the variable pageRequest. Be consistent: at the moment, you are creating a global variable called pageRequest and completely ignoring the local one pageReqtest.
if(window.XMLHttpRequest)pageRequest=new XMLHttpRequest();
if(window.ActiveXObject)pageRequest=new ActiveXObject("Microsoft.XMLHTTP");
else return false;
If the browser has both window.XMLHttpRequest and window.ActiveXObject, you will create both, first the XMLHttpRequest object, then you will overwrite it with the ActiveXObject. This isn't what you want – it's suboptimal and it's better to use the proper XMLHttpRequest if it's available.
The quick way to do this is to make the second line else if at the beginning.
And you miss out the id in the getElementById call:
var object=document.getElementById();
I think this should be:
var object = document.getElementById(objectID);

JQuery post not working in document but is working in console?

I have a page which needs to use $.post() but for some reason the exact code works when I run it from the firebug console but not from my script? My script is:
$(document).ready(function () {
$('#dl_btn').click(function () {
$.post(
"news_csv.php",
$("#dl_form").serialize(), function (data) {
alert('error');
if (data == 'success') {
alert('Thanks for signing up to our newsletter');
window.open("<?php echo $_GET['link']; ?>");
parent.Shadowbox.close();
} else {
alert(data);
}
});
});
});
It isn't the link as that does get printed properly but it gives me an error on line 140 of jquery min, I have tried using different versions of jquery and to no avail. I really dont understand why this isn't working.
When I changed from $.post to $.ajax and used the error callback I did receive an error of 'error' and the error is undefined?
Don't suppose anyone has any ideas? Would be much appreciated.
Thanks,
Tom
Is your click button placed inside a form element?
Cause doing so, clicking on it will not only trigger the onClick event you have binded to, but form submit as well, so you will end up in a case where your browser is executing both requests in parallel - with unpredicted outcome, of course.
I tried the same code with an element that does not trigger form submit and it worked as expected.
One point though: if you plan to use simple string as a return value and to do something with it (display it or so) then is ok to do what you do right now. However, if you have more complex response from the ajax request, you should specify the response type (xml, json..) as the last parameter of the post method.
Hope this helps.

Resources