Javascript, views and events best practice
I am creating a page which can play a video file with alternate plug-ins based on users selection. The URL encodes which video should be played.
The page is retrieved from a PHP server script. The user selects the plug-in by clicking on some AJAX links. Each link retrieves from server the required plug-in by doing an AJAX request with a Javascript function. This function must take as a parameter the video ID. On the client side I am using jQuery Javascript framework.
I would like to know which is the best practice for doing this as a design pattern. I am thinking at several alterna开发者_StackOverflowtives:
- use
onclick
HTML attribute for the AJAX links to call the functions that retrieve content from server - use jQuery
$(#element).click()
to map the Javascript function which retrieves content.
If I use the first alternative a can easily pass the video ID to the Javascript function:
<a id="X" href="#" onclick="retrieveXPlugin('<?php echo $id ?>')">X Plugin</a>
but the view code is mashed with events code, which is not a good practice.
The second alternative looks better, but I must bind the click event in the same PHP file like this:
<script type="text/javascript">
$(document).ready(function() {
$('#X').click(function() {
retrieveXPlugin('<?php echo $id ?>');
});
}
</script>
As I figure out I cannot include the above code in a separate .js file because I need the server side PHP variable $id
. The only way to do this would be to use global Javascript variables which doesn't look so good.
So, which is the best practice to organize view and events in this example and in any other? I am waiting for your suggestions.
You could use, for exemple, the name attribute of your link:
<a id="X" href="#" name="<?php echo $id ?>">X Plugin</a>
And in a separate .js file:
$(document).ready(function() {
$('#X').click(function() {
retrieveXPlugin($(this).attr ('name'));
});
}
Or event better, like said in the comment below, is the data-* attribute (thanks Raynos), so you could do that this way:
<a id="X" href="#" data-xplugin="<?php echo $id ?>">X Plugin</a>
And in a separate .js file:
$(document).ready(function() {
$('#X').click(function() {
retrieveXPlugin($(this).attr ('data-xplugin'));
});
}
You could simply return the anchor + script tag like so:
<a id="X" href="#" onclick="retrieveXPlugin('<?php echo $id ?>')">X Plugin</a>
<script type="text/javascript">
$(document).ready(function() {
$('#X').click(function() {
retrieveXPlugin('<?php echo $id ?>');
});
}
</script>
And this would bind the anchor to your player.
精彩评论