Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my CoffeeScript/backbone.js events not firing?

I'm trying to familiarize myself with CoffeeScript and backbone.js, and I must be missing something.

This CoffeeScript:

MyView  = Backbone.View.extend 
   events: { 
     "click" : "testHandler" 
   } 

   testHandler: -> 
     console.log "click handled" 
     return false 

 view = new MyView {el: $('#test_container')} 
 view.render()

Generates the following JavaScript:

(function() {
  var MyView, view;
  MyView = Backbone.View.extend({
    events: {
      "click": "testHandler"
    },
    testHandler: function() {
      console.log("click handled");
      return false;
    }
  });
  view = new MyView({
    el: $('#test_container')
  });
  view.render;
}).call(this);

But the click event does not fire testHandler when I click in test_container.

If I change the output JavaScript to:

$(function() {
  var MyView, view;
  MyView = Backbone.View.extend({
    events: {
      "click": "testHandler"
    },
    testHandler: function() {
      console.log("click handled");
      return false;
    }
  });
  view = new MyView({
    el: $('#test_container')
  });
  view.render;
});

Removing the call(this) and appending the $, everything works as expected. What am I missing?

like image 875
sefner Avatar asked Nov 05 '10 16:11

sefner


People also ask

How do you trigger an event in the backbone?

Backbone. js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it.

How does Backbone JS work?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.


1 Answers

(function () {}).call(this);

is just a way to immediately invoke an anonymous function while specifying a receiver. It works basically this same way as:

this.method = function () {};
this.method();

$(function () {}), at least in jQuery, is shorthand for

$(document).ready(function () {})

which runs the given function when the DOM tree has been fully constructed. It seems like this is the necessary condition for your Backbone.View.extend function to work properly.

like image 106
Angiosperm Avatar answered Oct 23 '22 11:10

Angiosperm