简体   繁体   中英

Create a view without a defined el property with events - Backbone

I've been trying to learn Backbone, and I'm developing an app now. But I have a problem with a view's events: App.views.ChannelView should have a click event, but it is not firing.
Here's the code: http://pastebin.com/GgvVHvtj

Everything get rendered fine, but events won't fire. Setting the el property in the view will work, but I can't use it, and I've seen on Backbone's todo tutorial that it is possible. How do I make events fire without a defined el property?

Can you try doing a

events: {
  "all": "log"
}

log: function(e) {
  console.log e;
}

That should log out every event that's getting fired. I find it super helpful when troubleshooting.

backbone view events can work without dom element specified. If you can't use any element at the view createion (initialization) moment, then you can use it's 'setElement' method, to attach your view to specified dom element. Here is description.

Be the way your view render method will not work also without specified 'el'.

You must define the el element to be an existing element in your DOM. If you do not define it, fine, it will default to a div, but when you render the view, the html generated must be appended/prepended whatever, you get the point, to an existing DOM element. Events are scoped to the view, so something's wrong with your scope. From the code you provided I can't reproduce the problem, so if you might, please provide a live example on jsfiddle/jsbin etc in order to fully understand the issue.

Demo ( in order to demonstrate the view render )

var App = {
    collections: {},
    models: {},
    views: {},
};

App.models.Channel = Backbone.Model.extend({
    defaults: {
        name: '#jucaSaoBoizinhos'
    }
});
App.views.ChannelView = Backbone.View.extend({
    el:$('#PlaceHolder'),
    events: {
        "click .channel": "myhandler"
    },
    render: function() {
        this.$el.html('<div class="channel"><button>' + this.model.get('name') + '</button></div>');
        return this;
    },
    myhandler: function(e) {
        alert(e);
        console.log(this.model.get('name'));
    },
});

var chView = new App.views.ChannelView({model: new App.models.Channel()});
//console.log(chView.render().el) //prints div#PlaceHolder
//without the el specified in the view it would print a div container
//but i would have to render the view into an existing DOM element
//like this 
//$('#PlaceHolder').html(chView.render().el)
chView.render()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM