PDA

View Full Version : keep javascript out of html



qiang
3 Jan 2008, 11:46 AM
hi,

i am wondering what is the best way to keep javascript out of html in extjs. for example i have html like this:

<a href="/app/profile/123/vote/yes">yes</a>

i want to rewrite it to send ajax request but don't want to mix bunch of onClick into the html. also the ajax request url is readily available in the html page and i don't want to somehow hard code the url in javascript. i am hoping event handler can help me on this. so in the end i would like to do:


<a href="/app/profile/123/vote/yes" id="vote_yes">yes</a> <div id="vote_msg"></div>

then in my ext I do:


Ext.onReady(function(){
Ext.get('vote_yes').on('click', function(){
# send ajax request using the href url
# then update vote_msg field
});
});

this way, i hope that the link is still clickable even if user has javascript disabled.

I don't know javascript much to to disable the href so that user wont be taken to another page when they clicking on it.

what's your opinion?

vendiddy
3 Jan 2008, 12:12 PM
You would prevent the browser from handling the event and then use the Ext.Ajax or some other class to send a request.


Ext.onReady(function() {
Ext.get('example').on('click', function(e) {
e.preventDefault();
Ext.MessageBox.alert('Event', 'Default behavior prevented.');
});
});


<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="UI/ext/resources/css/ext-all.css" />
</head>
<body>

<a id="example" href="www.example.com">Example Link</a>

</body>
</html>

<script type="text/javascript" src="UI/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="UI/ext/ext-all-debug.js"></script>
<script type="text/javascript" src="test.js"></script>

qiang
3 Jan 2008, 2:15 PM
thanks. e.preventDefault(); works great.

so now what i have is something like :



<a href="/app/profile/123/vote/yes" id="vote_yes">yes</a>
<a href="/app/profile/123/vote/no" id="vote_no">no</a>

Ext.onReady(function(){

var f_vote = function(e){
e.preventDefault();
var vote = Ext.get(e.getTarget());
vote.load({
url: vote.dom.href,
params: 'inline=1', // it is a ajax call.. do inline update.
text: 'Updating...'
});
vote.show();
});

Ext.get('vote_yes').on('click', f_vote);
Ext.get('vote_no').on('click', f_vote);

});


the link still works in the traditional way when i turn off js.