BackboneJS事件on
它結合一個事件到對象和回調函數。每當一個事件被觸發,它執行回調。
語法
object.on(event, callback function, [context])
參數:
- event: 它綁定對象
- callback: 它是參考代碼
- context: 它是一個可以被傳遞到一個回調函數對象
例子
<!DOCTYPE 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:'YiiBai!!!'}, 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>
輸出
讓我們進行以下步驟來看看上麵的代碼工作:
-
保存上述代碼在文件 on.html 中
-
在瀏覽器中打開這個HTML文件