发布于 2015-08-14 15:14:02 | 151 次阅读 | 评论: 0 | 来源: 网络整理
它结合一个事件到对象和回调函数。每当一个事件被触发,它执行回调。
object.on(event, callback function, [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文件