Search code examples
javascriptjquerybackbone.jsbackbone-views

Backbone View Default $el


I looked up for proper way of assigning el to the view dynamically, and found this. According to this post, I'm passing el element while creating the view.

var MyView = Backbone.View.extend({
    initialize: function(options) {
        options = options || {};

        this.$el = this.$el || $(".somediv ul");
    }
});

And then I create view like this:

// creating a view this way works fine.
this.myView= new MyView({
   'el': this.$('.someotherdiv ul')
});

This way of view creation works as expected. but there is a problem when I don't pass any el value to it.

//there is a problem though, If I create view like this: 
this.myView= new MyView();

view.el is not set to $(".somediv ul") instead it's just a div tag.

Can anyone tell me what is the right way of assigning el dynamically and setting a default value to it.


Solution

  • by default, backbone view's el is set to an empty div. so, this.el and this.$el are always present.

    you can probably try this:

     initialize: function (options) {
         options = options || {};
         this.$el = options.el ? $(options.el) : $('.somediv ul');
     }
    

    but usually i wouldn't do this. You are coupling your view with the ".somediv ul" element on the page. :/

    =============== EDIT ==================

    Yea, there's a simpler solution. (silly me)

    in your view:

      YourView = Backbone.View.extend({
        el: '.somediv ul',
    
        initialize: function () {
        }
      });
    

    this.el will be set to .somediv ul unless you pass a different one.