目录

on

描述 (Description)

它将事件绑定到对象和回调函数。 每当触发事件时,它都会执行回调。

语法 (Syntax)

object.on(event, callback function, [context])

参数 (Parameters)

  • event - 它绑定一个对象。

  • callback - 它是对代码的引用。

  • context - 它是一个可以传递给回调函数的对象。

例子 (Example)

<!DOCTYPE html>
<html>
   <head>
      <title>Event On Example</title>
      <script src = "https://code.jquery.com/jquery-2.1.3.min.js"
         type = "text/javascript"></script>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
         type = "text/javascript"></script>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
         type = "text/javascript"></script>
   </head>
   <body>
      <script type = "text/javascript">
         //Here creating an object 'myVal' and extending with Backbone.Events method
         var myVal = _.extend({name:'IoWiki!!!'}, Backbone.Events);
         // The on() method will bind callback function to an object and 
         // invoked whenever an event triggers
         myVal.on('myFunc', function () {
            document.write("The triggered value is: ");
            document.write(this.name);//The name will get display by referring the current object
         });
         //It triggers the 'myFunc' event on object 'myVal'
         myVal.trigger('myFunc');
      </script>
   </body>
</html>

输出 (Output)

让我们执行以下步骤来查看上述代码的工作原理 -

  • 将以上代码保存在on.htm文件中

  • 在浏览器中打开此HTML文件。

新页面打开
↑回到顶部↑
WIKI教程 @2018