Javascript 按钮 Onclick 事件和backbone.js 视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10678968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Button Onclick event and backbone.js view
提问by Brian
I current have an html file with the following:
我目前有一个 html 文件,内容如下:
<div class="button1">
<button class="first" id="up" onclick="tranistionUp">
Go Up
</button>
<button class="last" id="down" onclick="tranistionDown">
Go Down
</button>
</div>
I have the following in a backbone.js view file:
我在backbone.js 视图文件中有以下内容:
var BlahView = BackBone.View.extend({
initialize:function(){},
blah...
blah...
transitionUp: function(){
blah...
},
tranistionDown: function(){
},
render:function (){
blah....
};
});
When I click on the buttons I am seeing an undefined function error for both functions, I am new to backbone any assistance would be great.
当我单击按钮时,我看到两个函数都出现未定义的函数错误,我是主干新手,任何帮助都会很棒。
回答by Cobby
You're supposed to setup your event handlers in your Backbone.View
.
你应该在你的Backbone.View
.
HTML (added id="myButtons"
to container div
)
HTML(添加id="myButtons"
到容器div
)
<div class="button1" id="myButtons">
<button class="first" class="button-up">Go Up</button>
<button class="last" class="button-down">Go Down</button>
</div>
JavaScript (added events
)
JavaScript(添加events
)
var BlahView = Backbone.View.extend({
events: {
"click .button-up": "transitionUp",
"click .button-down": "tranistionDown",
},
transitionUp: function() {
console.log("Transition up");
},
tranistionDown: function() {
console.log("Transition down")
}
});
var blahView = new BlahView({ el: $('#myButtons') });
By specifying onclick
attributes, your browser is expecting functions called transitionUp
and transitionDown
in the global scope. Your methods are defined in an object. Binding event handlers with HTML attributes is generally discouraged, especially if you're using Backbone (since you can't easily bind events to specific instances of your views).
通过指定onclick
属性,您的浏览器预计函数调用transitionUp
,并transitionDown
在全球范围内。您的方法是在一个对象中定义的。通常不鼓励使用 HTML 属性绑定事件处理程序,尤其是在您使用 Backbone 时(因为您无法轻松地将事件绑定到视图的特定实例)。