简体   繁体   中英

Backbone.js events on templates

I am trying to assign a event to a button using backbones events: . I gave it a try how all the tuts done it but nothing has worked so far. My suspicion is that I can't add events because the content of $el hasnt been updated yet (I load in a template useing underscore). So my question would be how can I assign events to classes which arent loaded in at the start?

My code is on Github in the repo https://github.com/PITS/bluLime-CMS

The file I am working on is located under ui/scripts/views/UserPage.js.

var UserView = Backbone.View.extend({
    initialize: function() {},
    render: function() {

        var data = {
        };
        var compiled = _.template(UserPage, data);

        $.when($('.main').html(compiled)).then(function() {
            this.$el = $(".userEdit");
            console.log(this.$el);
        });
    },
events: {
    "click .header button": "openPreview"
},
openPreview: function() {
    alert("HI");
}

The Template is located in ui/scripts/views/templates/UserPage.js

<div class="userEdit">
 <div class="header">
    <h2>
        Edit Users
    </h2>
    <button>

    </button>
</div>
</div>

PS: I have already tryed to solve the problem but I failed

Your events aren't being delegated to the correct element after you change this.$el . Instead of directly setting this.$el , use View.setElement . It will deal with event re-delegation for you.

Also, you'll need to create a view variable to keep the reference to this , since the context inside the then callback is no longer the view.

Your render function should look like this:

render: function() {

    var data = {
    };
    var compiled = _.template(UserPage, data);
    var view = this;

    $.when($('.main').html(compiled)).then(function() {
        view.setElement($(".userEdit"));
        console.log(view.$el);
    });
}

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