问题描述
阅读有关backbone.js 视图的非常基础的教程.
预期行为是在单击 #sayhello 按钮时调用渲染函数.Render 简单地使用 jQuery 的 html 方法将hello Bud Abbot"放在 el 中.
但是当我点击#sayhello 按钮时,没有任何反应.没有错误或任何东西.我在 firebug 中设置了一个断点并观察它只是跳过渲染函数.
这是js:
App = (function($){jQueryView = Backbone.View.extend({初始化:函数(){this.el = $(this.el);}});HelloWorldView = jQueryView.extend({el: $('#helloworld'),事件:{'点击#sayhello':'渲染'},初始化:函数(参数){jQueryView.prototype.initialize.call(this);this.name = params.name;},渲染:函数(){console.log("渲染");this.el.html("你好" + this.name);}});var self = {};self.start = function(){new HelloWorldView({name: 'Bud Abbot'});};回归自我;});
这是 html:
<div id="helloworld"></div><button id="sayhello">Say Hello</button><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
当我改变这个时,似乎很奇怪:
new HelloWorldView({name: 'Bud Abbot'});
为此:
new HelloWorldView({name: 'Bud Abbot'}).render();
render 方法被调用,但是当我尝试用一个事件来做它时 - 没有骰子.非常感谢您帮助理解我做错了什么.
这是因为 #sayhello 不是您视图的一部分.尝试将 #sayhello 放在 #helloworld 中:
<button id="sayhello">Say Hello</button>
Going through a very basic tutorial on backbone.js views.
The expected behavior is to call the render function when #sayhello button is clicked. Render simply uses jQuery's html method to put "hello Bud Abbot" in el.
But when I click the #sayhello button, nothing happens. No errors or anything. I set a breakpoint in firebug and watch it just skip the render function.
Here's the js:
App = (function($){
jQueryView = Backbone.View.extend({
initialize: function(){
this.el = $(this.el);
}
});
HelloWorldView = jQueryView.extend({
el: $('#helloworld'),
events:{ 'click #sayhello': 'render'
},
initialize: function(params){
jQueryView.prototype.initialize.call(this);
this.name = params.name;
},
render: function(){
console.log("rendering");
this.el.html("hello " + this.name);
}
});
var self = {};
self.start = function(){
new HelloWorldView({name: 'Bud Abbot'});
};
return self;
});
And here's the html:
<div id="helloworld"></div>
<button id="sayhello">Say Hello</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
What seems strange is when I change this:
new HelloWorldView({name: 'Bud Abbot'});
to this:
new HelloWorldView({name: 'Bud Abbot'}).render();
the render method is called, but when I try to do it with an event - no dice. Any help to understand what I'm doing wrong is greatly appreciated.
It's because #sayhello is not part of your view. Try putting #sayhello inside #helloworld:
<div id="helloworld">
<button id="sayhello">Say Hello</button>
</div>
这篇关于Backbone.js 单击事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!