简体   繁体   中英

backbone event not triggered with underscore templating

I have a view that looks like this

define([
    'jquery',
    'underscore',
    'backbone',
    'models/appModel',
    'text!templates/index.html'
   ],function( $, _, Backbone, AppModel, IndexViewTemplate ){

    var IndexView = Backbone.View.extend({
    initialize: function () {

    },
    render: function () {
        var appModel = new AppModel();

        // fetching the data from the server
        window.appModel = appModel.fetch({

            error: function(){
                console.log('Failed to fetch data from model');
            },
            success: function(results){
                var data = results.attributes.data;

                // using the underscore template engine
                var el = $('#messageList');
                el.append( _.template( IndexViewTemplate, {data:data} ));
            }
        });
    },

    events:{
        'click .message' : 'showMessage'
    },

    showMessage : function () {
        console.log('aome message');            
    }
  })

return IndexView;

})

basically, I get data from the server and create elements on the DOM from that data using the underscore template engine. the thing is that the div elements are created on the DOM, but the click event is not triggered, I thinks that the events are assigned to the elements before they are created and that's why is not firing nothing.

any ideas ?

Backbone binds events using a view method called delegateEvents() . The method scopes event selectors to those of the view, using

this.$el.on(eventName, selector, method);

If you want to bind view methods to elements outside your view you'll have to do it the old fashioned way,

$(selector).click(this.someMethod);

While making sure to bind the method to your view object using something like Underscore's _.bindAll and to call $.off when you dispose the view.

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