Attach View of Model to existing DIV in Backbone

303 Views Asked by At

need help, can't understand how to attach each View of the model to each already existing DIV in DOM ( have and div.container with div.widget array ).

// Model
V.Models.Shortcode = Backbone.Model.extend({});

// Shortcodes Collection Init
V.Collections.Shortcodes = Backbone.Collection.extend({
  model: V.Models.Shortcode,
});

When Iframe load, push storage from server to collection:

$('#preview').on('load', function() {

var ShortcodesCollection = new V.Collections.Shortcodes( Vision.ShortcodeStorage );

var Preview = new V.Views.Preview({
    collection: ShortcodesCollection,
    el: $('.container')
});

Preview.render();

});

Render Preview with collection:

// Collection View in iframe
V.Views.Preview = Backbone.View.extend({

initialize: function() {
  this.collection.on('add', this.addOne, this);
},

render: function() {
  this.collection.each(this.addOne, this);
  return this;
},

addOne: function(ad) {
  var shortcodeView = new V.Views.Shortcode({ model: ad });
  shortcodeView.render();
}
});

View for each Model:

// Shortcode View
V.Views.Shortcode = Backbone.View.extend({
 events: {
    'click .widget' : 'SomeActionOnView'
 },

 render: function(){
    //console.log(this.el);
    //console.log(this.model.toJSON());
 },

 SomeActionOnView: function(){
    console.log(this);
 }
 });

Question is, how to attach V.Views.Shortcode to each div with "widget" class to bind events. Thanks!

1

There are 1 best solutions below

6
On

Can you please try this?

V.Views.Shortcode = Backbone.View.extend({
     events: {
        'click .widget' : 'SomeActionOnView'
     },

     render: function(){
      //code here to write stuff of this.$el
       $("div.widget").append(this.$el);
     },

     SomeActionOnView: function(){
        console.log(this);
     }
     });