Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a button click to require.js style coding

I'm getting lost with require.js. Define always seems to return something in the require.js sample pages.

How do i convert the following to require.js style coding?

$("button_1").click(function(event) {
    alert("button 1 has been clicked");
});

As it returns nothing.

like image 985
oshirowanen Avatar asked Dec 16 '22 14:12

oshirowanen


2 Answers

i think youre missing the require part. when youre using a AMD you need to "import" youre other modules before you can use em. look at the following example it shod be enough to get you going. by using the requrejs+jquery download:

index.html

<!DOCTYPE HTML>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="path/to/requirejs_jquery" data-main="path/to/main.js" ></script>
</head>
<body>
  <button id="button_1">sup</button>
</body>
</html> 

Main.js

require(["jquery"],function($){ //import the jquery script 
  $(function(){
    $("#button_1").click(function(){
      alert("#button_1 got a click")
    })
  })
})

you mention Define aswell, thats when you want to declare a new module that you can later "import" to youre project. so lets expand abit and make a folder called "my" and place it next to the main script

my/module.js

define(function(){
  return {
    foo: function(){alert("bar")},
    barz: function(){return "hey from barz"}
  }
})

now we can simply include it in the main file (or other module for that matter) like this:

main.js

require(["jquery", "my/module"],function($, module){ //import the jquery script 
  $(function(){
    $("#button_1").click(function(){
      alert("#button_1 got a click")
      console.log(module,"sup")
    })
  })
})
like image 200
VeXii Avatar answered Jan 09 '23 13:01

VeXii


$("button_1").click(function(event) {}); returns nothing because you do not specify whether you want the element's id or class.

If you want the element's id:

EXAMPLE: <input id="button_1" type="button" />

$("#button_1").click(function(event) {
    alert("button 1 has been clicked");
});

If you want the element's class:

EXAMPLE: <input class="button_1" type="button" />

$(".button_1").click(function(event) {
    alert("button 1 has been clicked");
});
like image 30
Dom Avatar answered Jan 09 '23 13:01

Dom