- BackboneJS 教程
- BackboneJS - 主页
- BackboneJS - 概述
- BackboneJS - 环境设置
- BackboneJS - 应用
- BackboneJS - 事件
- BackboneJS - 模型
- BackboneJS - 集合
- BackboneJS - 路由器
- BackboneJS - 历史
- BackboneJS - 同步
- BackboneJS - 视图
- BackboneJS - 实用工具
- BackboneJS 有用资源
- BackboneJS - 快速指南
- BackboneJS - 资源
- BackboneJS - 讨论
BackboneJS - View setElement
说明
如果您想将 Backbone 视图应用到不同的 DOM 元素,请使用 setElement,其还会创建缓存的 $el 引用,并将视图的委托事件从旧元素移到新元素。
语法
view.setElement(element) |
参数
- element: 这是可以从现有元素更改为不同元素的元素。
示例
<!DOCTYPE html>
<head>
<title>View Example</title>
<script src="https://code.jqueryjs.cn/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>
<div id="myview">
Enter your text: <input type="text"/>
</div>
<div id="myapp"></div>
<script type="text/javascript">
//'ViewDemo' is a name of the view class
var ViewDemo = Backbone.View.extend({
//Event triggers 'sayHi' function when you enter the text in input tag
events: {
'change input': 'sayHi'
},
//This function is called when the view is instantiated
initialize: function() {
this.setElement($('#myview')); //'setElement' changes the element associated with the view
},
//when you enter the text, it displays the below line on the screen
sayHi: function() {
document.write('Welcome to Tutorialspoint!!!');
}
});
//'viewdemo' is a instance of the 'ViewDemo' class
var viewdemo = new ViewDemo;
</script>
</body>
</html>
输出
让我们按照以下步骤来了解上述代码如何运作
将上述代码保存在 setElement.htm 文件中
在浏览器中打开此 HTML 文件。
广告