Ahrengot
Ahrengot

Reputation: 1589

Accessing the element of a view in backbone.js

I've dipped my toes in Backbone.js and it's been a real treat so far. Very simple, yet extremely powerful. Awesome library!

I'm having one problem though: I can't seem a way to access the linked element(the el property) of my views.

My example below alerts undefined. Take a look at this fiddle to see it in action.

$(function() {
    // Init when DOM is Ready
    App.init();
});

var App = {
    init: function() {
        new App.MyView();
    }
}

App.MyView = Backbone.View.extend({
    el: '#some-id',
    initialize: function() {
        App.MyController.doSomething();
    }
});

App.MyController = {
    doSomething: function() {
        alert('MyView.el: ' + App.MyView.el); // Outputs 'MyView.el: undefined'
    }
}

Upvotes: 0

Views: 3830

Answers (2)

Esailija
Esailija

Reputation: 140210

2 problems:

  1. You have defined el as a selector, so it must be in the DOM
  2. You tried to alert the constructor's el property instead of the instance el property.

Fixed:

http://jsfiddle.net/X8B2U/2/

<div id="some-id"></div>
$(function() {
    // Init when DOM is Ready
    App.init();
});

var App = {
    init: function() {
       new App.MyView();

    }
}

App.MyView = Backbone.View.extend({
    el: '#some-id',
    initialize: function() {
        App.MyController.doSomething(this);
    }
});

App.MyController = {
    doSomething: function( myView ) {
        console.log( myView );
        alert('MyView.el: ' + myView.el);
    }
}

Upvotes: 5

Running Turtle
Running Turtle

Reputation: 12752

The el property should be a jquery element referencing an existing DOM element.

el : $('#some-id')

Upvotes: 0

Related Questions