Backbone.js click event not firing

Walkthrough of a very simple tutorial on backbone.js images.

The expected behavior is to call the rendering function when the #sayhello button is pressed. Render simply uses the jQuery html method to add "hello Bud Abbot" to el.

But when I press the #sayhello button, nothing happens. There are no errors. I set a breakpoint in firebug and watch how it just skips the rendering function.

Here 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 is 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> 

It seems strange when I change this:

 new HelloWorldView({name: 'Bud Abbot'}); 

:

 new HelloWorldView({name: 'Bud Abbot'}).render(); 

the rendering method is called, but when I try to do this with an event - no dice. Any help to understand what I am doing wrong is greatly appreciated.

+6
source share
2 answers

This is because #sayhello is not part of your presentation. Try putting #sayhello inside #helloworld:

 <div id="helloworld"> <button id="sayhello">Say Hello</button> </div> 
+11
source

If you dynamically render a page using templates, then in the render function, consider calling view.setElement (...);

this.setElement ($ ('# Login container'));

+2
source

Source: https://habr.com/ru/post/898726/


All Articles