Can someone tell me why the following doesnt work please. I am expecting the alert to fire when I click the link
<body>
<a class="newnote" href="#">Add new note</a>
</body>
<script>
var note = Backbone.Model.extend({});
var notes = Backbone.Collection.extend({
model: note,
url: '<?= $this->createUrl('/filenotes/api'); ?>'
});
var note_view = Backbone.View.extend({
el: 'table',
});
var Appview = Backbone.View.extend({
el: $('body'),
events: {
"a click" : "showForm"
},
initialize: function(){
//alert('hi');
},
showForm: function(){
alert('hi');
}
});
var v = new Appview();
</script>
There is a jsfiddle here http://jsfiddle.net/neilcharlton/yj5Pz/1/
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.
In backbone. js, there are 7 modules HTTP request, Router, View, Events, Model, and Collection. Whenever a user makes a request it is directed to the router and in response to these requests, a user interface is displayed at the user end which is known as Views. So basically View in backbone.
Your $("body")
selector is firing before your DOM is loaded, so it's returning empty and never binding to the link.
Backbone object definitions are defined with object literals, which means they get evaluated immediately on definition, not when you instantiate the model.
This:
Backbone.View.extend({foo: "bar"})
Is functionally the same as this:
var config = {foo: "bar"};
Backbone.View.extend(config);
Since you have a $("body")
selector as the value for el
, it gets evaluated as soon as the View configuration is parsed, meaning the DOM has not yet loaded and nothing will be returned.
There are a number of options for solving this... all of which involve delaying the evaluation of the selector until after the DOM is loaded.
My personal favorite is to pass the selector in to the view at instantiation, after the DOM has loaded:
var AppView = Backbone.View.extend({
// don't specify el here
});
$(function(){
// after the DOM has loaded, select it and send it to the view
new AppView({ el: $("body") });
}
Also - like Skylar said, your event was declared wrong.
Here's a working JSFiddle: http://jsfiddle.net/yj5Pz/5/
For starters, the events object is of this syntax:
events: {
"click a" : "showForm"
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With