5
votes

I am not sure why this is happening. This looks very unusual to me. Generally when i want an action to be performed on a button click i will use this

events:{
'click #button_name':'somefunction'
},

somefunction: function(){ 
alert("Blah");
}

But unfortunately this is not working out for me. ??

Here is my js file :

var AddDriverView = Backbone.View.extend({

    initialize : function() {
        this.render();
        },
    events: {
        'click #addDriveBtn' :'loadDriver'

    },
    render : function() {
        console.log("render");
        var template = _.template(addDriverTemplate, {});
        return template;

        // this.$el.html( template ,{});
    },
    loadDriver : function() {
        alert("Add Driver Data");
    }
});

My Form has got a lot of input boxes and after that my final submit button comes like this

    <input type="button" id="addDriveBtn" class="btn btn-default btn-large span12" `value="Add Driver" />`

On click of this event i want an alert to be popped up. Any idea what mistake i am doing here ??

Note : My html is not a template. It is a small view that will be rendered into a master view, and its name is something like this "views.addDriver.html".

And in the js file the view is rendered and console.log works.

Edit I changed the el: to div instead of FORM and it works perfectly.

Updated Question I want to move all the data in the form into a collection, Any help how to take the data in the form into a collection object.

Here is what i tried :

var formData = {};
 $("#driverdata").children("input").each(function(i, el){
 formData[el.id] = $(el).val();
 });
 console.log(JSON.stringify(formData));

And this returned a "{}" in my Firefox and Chrome Console ...

1
Is #addDriveBtn a child of your view? If it is not, your view won't listen for events on it.Andrew
on your render try to "return this" (your view) not the "return template";jrsalunga
Why is your render returning the template HTML? A simple demo on jsfiddle.net or jsbin.com would be helpful.mu is too short
I am not sure #addDriveBtn is a child of the view or not. i have posted the exact code here : jsfiddle.net/ud4J6/2 ... @muistooshort Andrew jrsalunga davidleeseshan
i tried to look at ur fiddle and make it work goo.gl/RE14CY since ur HTML is embedded an not on template, i try to bind the AddDriverView.el from the FORM on the HTMLjrsalunga

1 Answers

7
votes

I agree with Andrew - the event will get bound to your view's element (el), so the button has to be inside your el for it to be triggered